2010-09-19 13 views
19

Sto provando a creare una funzione tema pagina per il mio sito. Voglio caricare i temi corrispondenti in modo dinamico sulla pagina utilizzando file CSS separati.Caricamento dinamico CSS

sto usando questo codice:

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

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

che funziona bene, ma non restituisce alcuna informazione se il file CSS è stato caricato o meno.

C'è un modo per prendere quando il .css viene caricato? Forse usando l'ajax?

+0

vedere collegamento utile qui http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/ –

risposta

20

Internet Explorer attiverà un evento onReadyStateChange quando viene caricato il file CSS (o qualsiasi altra modifica in esso è readyState). Altri browser non attivano nessun evento, quindi dovrai verificare manualmente se il foglio di stile è stato caricato, il che è facilmente possibile controllando l'oggetto document.styleSheets a intervalli fissi.

Esempio

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

E 'brutto, ma funziona in tutti i browser.

+1

Grazie! Haha, hai ragione sul fatto che sia brutto, ma fa il lavoro. – Moe

Problemi correlati