Tuesday, July 26, 2011

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:
  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() {
if (loadedScripts==src.length) {
for (var i=0; i<src.length; i++) {
var script=document.createElement('script');
// HTML5 only, but it could work
if (onload) {
if (typeof(script.onload)=='undefined'&&typeof(script.readyState)!='undefined') {
script.onreadystatechange=function() {
if(script.readyState=='complete'||script.readyState=='loaded') {
} else {
//not IE
script.onload=function() {

I hope it helps.