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
Just in case you find this useful, I've created an async utility library that would let you write the above code as:
var Loader = function () {}
Loader.prototype = {
require: function (scripts, callback) {
async.map(scripts, this.writeScript, callback);
},
writeScript: function(src, callback) {
var s = document.createElement('script');
s.type = "text/javascript";
s.src = src;
s.addEventListener('load', function (e) { callback(null, e); }, false);
var head = document.getElementsByTagName('head')[0];
head.appendChild(s);
}
}
If you're doing lots of asynchronous calls it has some quite powerful features :)
http://caolanmcmahon.com/async.html
Like Aaron says there's a bug in chrome,but there are also problems on IE and other browsers.
I tryed different ways to create my lazy loader and i had a lot of problems:
I recommend you use a tiny loader javascript like JcorsLoader (only 647B with Gzip)
JcorsLoader.load(
"http://xxxx/jquery.min.js",
function() {
$("#demo").html("jQuery Loaded");
},
"http://xxxx/jquery.cookie.js",
function() {
$.cookie('not_existing');
}
);
Load multiples js in parallel and execute in order without blocking DOMReady or onload.
https://github.com/pablomoretti/jcors-loader
What about jQuery....
$.getScript('abc.js');
Above code will load the "abc.js" script file asynchronously....
There is nothing wrong with your code from what I can tell, this is just a bug in Chrome (it does it with window.onload also.)
I'd add it to the function that is triggered in the "load" function. If the variable exists, execute the JS code, but if it doesn't, use a setTimeout to check again in 500ms or so.
jcors-loader.js not working in Internet Explorer...
Index.html
<html>
<head>
<script type="text/javascript" src="/js/jcors-loader.js"></script>
<script>
JcorsLoader.load(
"js/jquery-1.8.0.js",
"/js/alertme.js",
function() {
$("#result").text("TEST OK");
}
);
</script>
</head>
<body>
<h1 id="result"></h1>
</body>
</html>
alertme.js
alert("Loaded");
This works fine in chrome and firefox it displays "TEST OK" and popup...But no message or alert in IE(7,8,9)...Any help will be appreciated.