日期:2014-05-17  浏览次数:20646 次

动态加载JS/CSS文件
动态加载JS/CSS文件,可以判断是否加载完毕。
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 = null;
				callback();
			}
		};
	} else { // Others
		script.onload = function() {
			callback();
		};
	}
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
}

//例子
loadScript("file1.js", function(){
    alert("File is loaded!");
});
//顺序加载
loadScript("file1.js", function() {
		loadScript("file2.js", function() {
			loadScript("file3.js", function() {
				alert("All files are loaded!");
			});
		});
});