Note that there are some explanatory texts on larger screens.

plurals
  1. POAsync Load JavaScript Files with Callback
    text
    copied!<p>I am trying to write an ultra simple solution to load a bunch of JS files asynchronously. I have the following script below so far. However the callback is sometimes called when the scripts aren't actually loaded which causes a variable not found error. If I refresh the page sometimes it just works because I guess the files are coming straight from the cache and thus are there quicker than the callback is called, it's very strange?</p> <pre><code>var Loader = function () { } Loader.prototype = { require: function (scripts, callback) { this.loadCount = 0; this.totalRequired = scripts.length; this.callback = callback; for (var i = 0; i &lt; scripts.length; i++) { this.writeScript(scripts[i]); } }, loaded: function (evt) { this.loadCount++; if (this.loadCount == this.totalRequired &amp;&amp; typeof this.callback == 'function') this.callback.call(); }, writeScript: function (src) { var self = this; var s = document.createElement('script'); s.type = "text/javascript"; s.async = true; s.src = src; s.addEventListener('load', function (e) { self.loaded(e); }, false); var head = document.getElementsByTagName('head')[0]; head.appendChild(s); } } </code></pre> <p>Is there anyway to test that a JS file is completely loaded, without putting something in the actual JS file itself, because I would like to use the same pattern to load libraries out of my control (GMaps etc).</p> <p>Invoking code, just before the tag.</p> <pre><code>var l = new Loader(); l.require([ "ext2.js", "ext1.js"], function() { var config = new MSW.Config(); Refraction.Application().run(MSW.ViewMapper, config); console.log('All Scripts Loaded'); }); </code></pre> <p>Thanks for any help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload