使用JS動態在頁面載入CSS檔案

來源:互聯網
上載者:User

剛剛在寫隨筆的時候發現cnblogs好像將自己在文章的HTML裡定義的CSS(例如:<link rel="stylesheet" type="text/css" href="xxx.css" /> )都過濾掉了,記得以前自己收藏過一個JS函數,可以動態載入CSS檔案,翻翻電腦果然找到了,代碼貼出來,說不準在工作中也會用到呢。 

loadjscssfile
<script language="javascript">

    function loadjscssfile(filename, filetype) {
        if (filetype == "js") {
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename)
        } else if (filetype == "css") {
            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("http://news.163.com/special/0001jt/dblue.css", "css");
</

 

本地遠程都可以哦,呵。。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.