For more detailed description go to http://betterexplained.com/articles/speed-up-your-javascript-load-time/

1. Compress JavaScript using JSMin or Rhino. You can also just gzip it using the normal zip tools but some browsers will not be able to uncompress it automatically.

2. Optimise JavaScript placement. It is not always a good idea to place all the JavaScript files and the CSS files in the header. Place them right before they have to be loaded in order to display some page elements quickly. This will give the users a sense of immediate reponsiveness.

3. Load JavaScript on demand

function $import(src){
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src',src);
scriptElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

// import with a random query parameter to avoid caching
function $importNoCache(src){
var ms = new Date().getTime().toString();
var seed = "?" + ms;
$import(src + seed);
}

You can test it with the following code.

if (myfunction){
// loaded
}
else{ // not loaded yet
$import('http://www.example.com/myfile.js');
}

4. Combine your JavaScript files. Each file incurs the HTTP request and response costs.

5. Cache your scripts.

6. gzip your scripts.

Advertisements