2010-09-19 98 views
19

我正在尝试为我的网站创建页面主题功能。我想使用单独的CSS文件在页面上动态加载相应的主题。动态加载CSS

我使用这个代码:

fileref.setAttribute("rel", "stylesheet") 
    fileref.setAttribute("type", "text/css") 
    fileref.setAttribute("href", 'link.css') 

    document.getElementsByTagName("head")[0].appendChild(fileref) 

,工作正常,但如果CSS文件加载或没有它不返回任何信息。

加载.css时有没有办法捕获?也许通过使用Ajax?

+0

看到有用的链接在这里http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/ – 2010-09-19 02:21:05

回答

20

加载CSS文件(或其中的任何其他更改readyState)时,Internet Explorer将触发onReadyStateChange事件。 其他浏览器不会触发任何事件,因此您必须手动检查样式表是否已加载,这很容易通过以固定的时间间隔检查document.styleSheets对象。

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);  
} 

这是丑陋的,但它在所有浏览器上运行。

+1

谢谢!哈哈,你说它很丑,但是它做的很好。 – Moe 2010-09-19 14:02:18