动态加载CSS [英] Dynamically loading CSS
问题描述
我想创建一个网页的主题功能为我的网站。我想用单独的CSS文件动态加载相应的主题页面上。
I'm trying to create a page theme function for my site. I want to load the corresponding themes dynamically on the page using separate CSS files.
我用这个code:
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", 'link.css')
document.getElementsByTagName("head")[0].appendChild(fileref)
,工作正常,但如果CSS文件已加载与否不返回任何信息。
Which works fine, but it doesn't return any info if the CSS file has loaded or not.
有没有办法在的.css
加载时赶上?也许通过使用AJAX?
Is there a way to catch when the .css
is loaded? Maybe by using ajax?
推荐答案
Internet Explorer将触发时加载CSS文件或的onreadystatechange
事件(任何其他变化,它的的readyState
)。
其他浏览器不会触发任何事件,所以你必须手动检查样式表已被加载,这是很容易可以通过在固定的时间间隔检查 document.styleSheets
对象
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.
示例
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.
这篇关于动态加载CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!