本节内容:
异步动态加载JS与css文件
例子:
复制代码 代码示例:
(function(){
var ga=document.createElement('script');ga.type?=?'text/
javascript';?ga.async?=?true;
ga.src?=?('https:'?==?document.location.protocol???'https://ssl'?:?'http://www')?+?'.google-analytics.com/ga.js';
var?s?=?document.getElementsByTagName('script')[0];?
s.parentNode.insertBefore(ga,?s);
})();
2,异步动态加载js与css文件的js代码。
jquery动态加载css,js文件:
方法1:
复制代码 代码示例:
$.getscript("test.js");
方法2:
复制代码 代码示例:
function loadjs(file){
var head = $('head').remove('#loadscript');
$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}).appendto(head);
}
方法3:
复制代码 代码示例:
$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}).appendto($('head').remove('#loadscript'));
为大家提供一些js动态加载js,css文件的方法。
复制代码 代码示例:
<script>
var SCRIPT_TIMEOUT = 20000;
var QVPL_PATH = "/QVPL1.0.0.js";
function loadHelper (jsurl) {
var oScriptEl, oTimeoutHDL, oHead;
oScriptEl = document.createElement("script");
oScriptEl.type = "text/javascript";
oScriptEl.language = "javascript";
oScriptEl.src = jsurl;
oScriptEl.onreadystatechange = doCallback;
oScriptEl.onload = function()
{
this.readyState = "complete";
doCallback();
if(typeof(lianbo) == "object"){
lianbo.init(window.QVPL);
}
};
oTimeoutHDL = window.setTimeout(doError,SCRIPT_TIMEOUT);
document.getElementsByTagName("head")[0].appendChild(oScriptEl);
function doCallback()
{
if (oScriptEl.readyState == "complete" || oScriptEl.readyState == "loaded")
{
oScriptEl.onload = oScriptEl.onreadystatechange = new Function();
window.clearTimeout(oTimeoutHDL);
}
};
function doError()
{
oScriptEl.parentNode.removeChild(oScriptEl);
};
}
loadHelper(QVPL_PATH);
</script>