Internet Explorer will trigger an onReadyStateChange
event when CSS file is loaded (or any other change in it's readyState
).
Other browsers do not trigger any event, so you will have to manually check if the stylesheet has been loaded, which is easily possible by checking the document.styleSheets
object at a fixed interval.
Example
window.onload = function (){
var filename = "link.css",sheet,i;
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
readyfunc = function () {
alert("File Loaded");
}
timerfunc = function (){
for (i=0;i<document.styleSheets.length;i++){
sheet = document.styleSheets[i].href;
if(sheet !== null && sheet.substr(sheet.length-filename.length) == filename)
return readyfunc();
}
setTimeout(timerfunc,50);
}
if (document.all){ //Uses onreadystatechange for Internet Explorer
fileref.attachEvent('onreadystatechange',function() {
if(fileref.readyState == 'complete' || fileref.readyState == 'loaded')
readyfunc();
});
} else { //Checks if the stylesheet has been loaded every 50 ms for others
setTimeout(timerfunc,50);
}
document.getElementsByTagName("head")[0].appendChild(fileref);
}
It's ugly, but it works in all browsers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…