Dynamically load and unload stylesheets

前端 未结 3 389
-上瘾入骨i
-上瘾入骨i 2020-12-29 08:33

I\'ve searched various posts and forums but can\'t find the right answer. I need to find a way to dynamically load and unload stylesheets.

I\'m building a website th

3条回答
  •  星月不相逢
    2020-12-29 08:50

    I managed to get this working with a little tweaking of:

    http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

    Content of the link:

    function loadjscssfile(filename, filetype){
        if (filetype=="js"){ //if filename is a external JavaScript file
            var fileref=document.createElement('script')
            fileref.setAttribute("type","text/javascript")
            fileref.setAttribute("src", filename)
        }
        else if (filetype=="css"){ //if filename is an external CSS file
            var fileref=document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        if (typeof fileref!="undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    
    loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
    loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
    loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
    
    function removejscssfile(filename, filetype){
        var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
        var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
        var allsuspects=document.getElementsByTagName(targetelement)
        for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
        }
    }
    
    removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page though in most browser this does not unload the script
    removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page
    

    Just FYI: For js scripts, this will remove a script element from the DOM but most browser will not unload the js code i.e. anything defined in the js file will stay defined.

提交回复
热议问题