動態加載js和css


博客搬家了,歡迎大家關注,https://bobjin.com

開發過程中經常需要動態加載js和css,今天特意總結了一下常用的方法。

 1、動態加載js

  方法一:動態加載js文件

1     // 動態加載js腳本文件
2     function loadScript(url) {
3         var script = document.createElement("script");
4         script.type = "text/javascript";
5         script.src = url;
6         document.body.appendChild(script);
7     }
8     // 測試
9     loadScript("javascript/lib/cookie.js");

  方法二:動態加載js腳本

 1    // 動態加載js腳本
 2     function loadScriptString(code) {
 3         var script = document.createElement("script");
 4         script.type = "text/javascript";
 5         try{
 6             // firefox、safari、chrome和Opera
 7             script.appendChild(document.createTextNode(code));
 8         }catch(ex) {
 9             // IE早期的瀏覽器 ,需要使用script的text屬性來指定javascript代碼。
10             script.text = code;
11         }
12         document.body.appendChild(script);
13     }
14     // 測試
15     var text = "function test(){alert('test');}";
16     loadScriptString(text);
17     test();

2、動態加載css

  方法一:動態加載css文件

 1     // 動態加載css文件
 2     function loadStyles(url) {
 3         var link = document.createElement("link");
 4         link.type = "text/css";
 5         link.rel = "stylesheet";
 6         link.href = url;
 7         document.getElementsByTagName("head")[0].appendChild(link);
 8     }
 9     // 測試
10     loadStyles("css/secondindex.css");

  方法二:動態加載css腳本

 1    // 動態加載css腳本
 2     function loadStyleString(cssText) {
 3         var style = document.createElement("style");
 4         style.type = "text/css";
 5         try{
 6             // firefox、safari、chrome和Opera
 7             style.appendChild(document.createTextNode(cssText));
 8         }catch(ex) {
 9             // IE早期的瀏覽器 ,需要使用style元素的stylesheet屬性的cssText屬性
10             style.styleSheet.cssText = cssText;
11         }
12         document.getElementsByTagName("head")[0].appendChild(style);
13     }
14     // 測試
15     var css = "body{color:blue;}";
16     loadStyleString(css);

 

博客搬家了,歡迎大家關注,https://bobjin.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM