动态加载js和css

2017-02-16 15:14:14

开发过程中经常需要动态加载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);

复制代码

 


  • 2017-11-06 01:00:17

    撤销git add

    如何撤销git add,不小心执行了git add . 操作,但是又不能提交所有的文件,因为对应不同的分支,现在怎么样可以将git add 撤销回来

  • 2017-11-10 00:06:15

    CORS: credentials mode is 'include'

    XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.