2010-09-19 18 views
19

Estoy intentando crear una función de tema de página para mi sitio. Quiero cargar los temas correspondientes dinámicamente en la página usando archivos CSS separados.Cargando dinámicamente CSS

Estoy usando este código:

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

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

que funciona muy bien, pero no devuelve ninguna información si el archivo CSS ha cargado o no.

¿Hay alguna manera de detectar cuando se carga el .css? ¿Quizás usando ajax?

+0

ver enlace útil aquí http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/ –

Respuesta

20

Internet Explorer desencadenará un evento onReadyStateChange cuando se carga el archivo CSS (o cualquier otro cambio en el readyState). Otros navegadores no desencadenan ningún evento, por lo que deberá verificar manualmente si la hoja de estilo se ha cargado, lo cual es fácilmente posible al marcar el objeto document.styleSheets en un intervalo fijo.

Ejemplo

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

Es feo, pero funciona en todos los navegadores.

+1

¡Gracias! Jaja, tienes razón sobre que es feo, pero cumple su función. – Moe

Cuestiones relacionadas