I am trying to achieve the following:
- I have a server-side script that generates CSS 开发者_运维问答code depending on GET parameters
- On user request a JS should now do the following
- Load a new CSS file
- When loading is done, fade to the newly loaded style
Problem here is the last step.
It is no problem to add a new CSS file to the DOM, but how do I know when the browser finished loading the file? I cannot start animations using the newly loaded styles until the file is actually loaded.
Alternatively: Is it possible to load a CSS file using Async Requests, and inject the CSS code into the DOM using Javascript without parsing it by hand?
Thank you very much!
Dennis
I know this question is quite old, but in case anyone Googles this, here is a function that lets you define a callback to let you know when the stylesheet is loaded:
var css = function(url, callback) {
var head = document.getElementsByTagName('head')[0];
var cssnode = document.createElement('link');
cssnode.type = 'text/css';
cssnode.rel = 'stylesheet';
cssnode.href = url;
cssnode.onreadystatechange = callback;
cssnode.onload = callback;
head.appendChild(cssnode);
}
there are a nice library for this kind of filters...
maybe you can give that a try:
Yep Nope
Yepnope is an asynchronous conditional resource loader that's super-fast, and allows you to load only the scripts that your users need.
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
精彩评论