I was working on the chess board support on my blog, involving a third party javascript script. The idea was that, if any element on the page is of class pgn, then the parser should try to read the contents and transform it into a chess board.

Traditionally, what you would do is:
  1. load the external scripts
  2. load the external css files
  3. run a small initialization script that finds all the pgn elements and applies the transformation on them
. Now, imagine that I am doing several processes like this. On some blog posts I will talk about chess, but on other I would display some chart or have extra functionality. Wouldn't it be nice if I could only load the external scripts when I actually need them?

In order to do that, I must reverse the order of the steps. If I find pgn elements, I load external scripts. When loaded, I execute the initialization script. Long story short, here is a javascript function to load an external script (or several) and then execute a function when they are loaded:

function loadScript(src,onload) {
if (src&&typeof(src)!='string'&&src.length) {
//in case the first parameter is a list of items
var loadedScripts=0;
// execute the load function only if all the scripts have finished loading
var increment=onload
?function() {
loadedScripts++;
if (loadedScripts==src.length) {
onload(null);
}
}
:null;
for (var i=0; i<src.length; i++) {
loadScript(src[i],increment);
}
return;
}
var script=document.createElement('script');
script.type='text/javascript';
// HTML5 only, but it could work
script.async=true;
script.src=src;
if (onload) {
if (typeof(script.onload)=='undefined'&&typeof(script.readyState)!='undefined') {
//IE
script.onreadystatechange=function() {
if(script.readyState=='complete'||script.readyState=='loaded') {
onload(script);
}
};
} else {
//not IE
script.onload=function() {
onload(script);
};
}
}
document.body.appendChild(script);
}


I hope it helps.

Comments

Be the first to post a comment

Post a comment