If you need to know when JS is loaded use the following loadScript function. You might be able to do similarly for CSS, but I haven't tried it:
function preload(src, callback, node) { var script, ready, where; where = node || document.body; ready = false; script = where.ownerDocument.createElement('script'); script.src = src; script.onload=script.onreadystatechange=function(){ if ( !ready && ( !this.readyState || this.readyState == 'complete' ) ) { ready = true; callback(); script.parentNode.removeChild(script); } }; where.appendChild(script); }
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 script element to preload css instead of a link element.
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 link elements don't change the DOM (ignoring possible javascript insertion via url). 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 support onload, 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.