source

CSS를 동적으로 로드하는 중

nicesource 2023. 10. 11. 20:48
반응형

CSS를 동적으로 로드하는 중

제 사이트의 페이지 테마 기능을 만들려고 합니다.별도의 CSS 파일을 이용하여 해당 테마를 페이지에 동적으로 로드하고 싶습니다.

이 코드를 사용하고 있습니다.

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

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

이것은 잘 작동하지만 CSS 파일이 로드되었는지 여부에 따라 어떠한 정보도 반환하지 않습니다.

그 때 잡을 방법이 있나요?.css로딩되었습니까?아약스를 이용해서?

Internet Explorer(인터넷 익스플로러)가 트리거됩니다.onReadyStateChangeCSS 파일이 로드될 때 이벤트(또는 기타 변경 사항)readyState다른 브라우저에서는 이벤트가 발생하지 않으므로 스타일시트가 로드되었는지 수동으로 확인해야 하며, 이는 쉽게 확인할 수 있습니다.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);    
}

보기 흉하지만 모든 브라우저에서 작동합니다.

언급URL : https://stackoverflow.com/questions/3744270/dynamically-loading-css

반응형