Example of lazy loading asyncronous Javascript file.
/*
Lazy Loading Asyncronous Javascript
Requirements:
- Small. I don't want a big mess for them to include on their sites. 10-15
lines, tops.
- Stand-alone. The environment is unknown, so we can't rely on any external
dependencies, like javascript libraries.
- Cross-browser. I have no idea what browsers my customer's customers have, so I
can't do anything modern or fancy that isn't backwards compatible. I assume at
least IE6 and up though.
- Asynchronous download. The download of my script should not block the download
of any script on their sites.
- Lazy Loading. If my site is temporarily slow, I don't want to block the onload
event from triggering until after our site responds.
- Preserve events. Any events used should not override any events on the
customer's site. Minimal impact, like I said.
- Don't pollute namespace. Global variables should be avoided, since they could
conflict with existing javascript.
article: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
*/
(function () {
function asyncLoad() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent) {
window.attachEvent('onload', asyncLoad);
}
else {
window.addEventListener('load', asyncLoad, false);
}
})();