动态加载js的脚本

[该代码参考《高性能javascript》]

在</body>之前引入以下代码:

function loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    if (script.readyState) { // IE
	script.onreadystatechange = function() {
	    if (script.readyState == "loaded" || script.readyState == "complete") {
	        script.onreadystatechange = nill;
	        callback();
	    }
	};
    } else { // other browser
	script.onload = function() {
	    callback();
        };
    }
    script.src = url;
    document.getElementByTagName("head")[0].appendChild(script);
}

使用:

loadScript("file.js",function() {
    alert("loaded");
});

你可能感兴趣的:(js,动态加载)