Loading a Javascript external script conditionally and programatically from javascript
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:
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:
I hope it helps.
Traditionally, what you would do is:
- load the external scripts
- load the external css files
- run a small initialization script that finds all the pgn elements and applies the transformation on 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