I’m currently developing a mobile website which is heavy on the images, css and javascript (it uses a library which is 150KB uncompressed for example). I’ve constructed a preloader for the images which works rather nicely:
function loadImages(images){
var sum = 0;
for(i in images){
sum += images[i][1]; // file size
}
setMaxProgress(sum);
for(i in imageArray){
var img = new Image();
img.onload = function(){ addProgress(imageArray[i][1]); };
img.src = imageArray[i][0];
}
}
However I would now like to do something similar for the javascript and css, but there are a lot less resources available to do that. The only way I’ve found is to document.write() the html tags after the document is loaded but this doesn’t hive me a (reliable) indication of when the files are loaded.
Is there a way to do this while I can still measure progress?
BTW: I use this as an addition to normale optimizing techniques like minifying js/css, gzipping, css sprites and proper cache control, not as a replacement. Users can skip loading and the site works perfectly fine then, albeit less smoothly
If you need to know when JS is loaded use the following
loadScriptfunction.You might be able to do similarly for CSS, but I haven’t tried it:I’ve updated the function, and tested it in firefox. It works for both js and css (some cross-browser checking is required for css.
I’d also like to add a bit more information as to why you’d use the
scriptelement to preload css instead of alinkelement.When the page is being loaded, resources that affect the structure of the DOM need to be analyzed and inserted in the order that they appear. Script elements need to be executed in the context of the partially loaded DOM so that they affect only existing DOM nodes.
Stylesheets included via
linkelements don’t change the DOM (ignoring possible javascript insertion viaurl). It doesn’t matter if the stylesheet is loaded before during or after the DOM tree is parsed, so there’s no necessary callback as to when the resource is loaded. If a script element is used to link to a stylesheet, the external resource still needs to be loaded before the javascript interpreter can decide whether to perform any actions, or whether it should crash with an exception.If you preload each script in the context of a hidden iframe, you can contain all the errors to a separate context without crashing javascript running on the page.
One word of caution: external scripts that perform functions will still have a chance to execute before being removed. If the script is performing ajax polling or similarly unnecessary actions, consider not pre-loading that particular script.
You may be able to get around this using
'loaded'in the place of'complete', however there are some older browsers that only supportonload, so for those browsers the scripts would still be executed. Pre-loading is really meant to be used for library components that need to be called on various different pages.