Document.write fallback calls jQuery to unload

I am creating a new site using HTML5 Boilerplate 4.0 and I am having problems with its local jQuery backup code. This code is here:

<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> --> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.1.min.js"><\/script>')</script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> 

I am developing locally while I commented on the CDN line. My problem is that jQuery really loads, but loads after plugins.js and main.js, which leads to undefined errors.

The closest, perhaps the explanation I found, is point # 4 of this previous answer , which suggests that this was expected, but ... above is the most commonly used local backup code for jQuery, and this is H5BP, which is heavily tested. I have to miss something, right?

+2
source share
3 answers

I answered a similar question a while ago.

You can do something like this:

 function loadScript(pathToScript, callback) { if (/jquery/.test(pathToScript) && window.jQuery) { //jQuery has already been loaded so simply call the callback callback.apply(); } else { var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.type = "text/javascript"; script.src = pathToScript + "?t=" + new Date().getTime(); //prevent caching if (callback) { script.onload = callback; } head.appendChild(script); } } var scripts = ['js/vendor/jquery-1.8.1.min.js', 'js/plugins.js', 'js/main.js']; (function (i) { if (i < scripts.length) { var self = arguments.callee; loadResource(scripts[i], function () { self(++i); }); } })(0); 
0
source

I also did not find the exact answer to StackOverflow about this issue, however, it seems that this page covered the topic:

To summarize, creating a truly reliable resiliency solution is not easy. We need to consider browser incompatibilities, document states and events, dependencies, delayed loading and timeouts! Fortunately, tools like LABjs help us relieve pain by giving us complete control over the loading of our JavaScript files.

Note: solution depends on using LABjs

0
source

You can use yepnope to load your scripts in parallel with the backup.

On its website:

yepnope.js has the ability to backup resources and still load dependent scripts in parallel with the first.

And the code:

 yepnope([{ load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js', complete: function () { if (!window.jQuery) { yepnope('local/jquery.min.js'); } } }, { load: 'jquery.plugin.js', complete: function () { jQuery(function () { jQuery('div').plugin(); }); } }]); 

I hope this help!

0
source

All Articles