Is is possible to have an alternate source for a javascript in HTML5? For example, I am using jQuery, and have it locally. But an I allowed to include an alt
attribute so that if that doesn't work, Google's jQuery will load?
If it works, the code would look something like this: <script src="enter your text here.js" alt="googlescode"></script>
Is is possible to have an alternate source for a javascript in HTML5? For example, I am using jQuery, and have it locally. But an I allowed to include an alt
attribute so that if that doesn't work, Google's jQuery will load?
If it works, the code would look something like this: <script src="enter your text here.js" alt="googlescode"></script>
- There're many script loaders written in JavaScript. Shall we assume you want a static HTML solution? – Álvaro González Commented Sep 7, 2013 at 19:29
- Sure, but that is not what my question is about. – tjons Commented Sep 7, 2013 at 19:31
3 Answers
Reset to default 8Yes, you can do it. HTML5 Boilerplate has a good example for jQuery loading.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
But it uses it the other way around. If the script from google couldn't be loaded, it falls back to your local script.
You should load the CDN version as a first try anyway, as it loads quicker than a "local" version.
If it is jQuery, you might want to look at this article.
Snippet:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='/js/jquery-2.0.0.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
When implementing them I realized all the former answers have the common problem that Chrome will block them with slow connections since document.write
is a synchronous function.
The issue is discussed in this post.
The solution usually is using a moderns loader, or pre-compiling the js code.
However, if your use-case still requires this approach, you need to use an async call. An illustrative example is the way Google Analytics is loaded.
Basically, the code above translates into:
<script>window.jQuery || (function(){
// Create the DOM node
a=document.createElement('script');
a.src="http://path-to-the-script.js";
a.async=1;
// Find a node, and insert the script before it
m=document.getElementsByTagName('script')[0];
m.parentNode.insertBefore(a,m);
})()</script>