异步动态加载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文件的方法。
以下代码是摘自news.qq.com页面里的代码的,本人未进行测试,程序看着应该没有问题的,可以做为参考的,主要用来在网页底部位置,实现动态加载js文件到网页<head>标签的后面,通过DOM来实现的,代码如下:
<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>