日期:2014-05-16  浏览次数:20629 次

实战javascript之动态加载js和动态加载css

在整合ajax的项目中,动态加载js和动态加载css是必须的

动态加载js

// 动态加载JS
function add_js(name) {
	var head = document.getElementsByTagName('head').item(0);
	var headlist = head.childNodes;
	for(var i = 0;i < headlist.length;i = i+1){
		if(headlist[i] != "" && headlist[i].type == "text/javascript"){
			if(headlist[i].src.indexOf(name) > -1){						
				head.removeChild(headlist[i]);
				break;
			}
		}
	}
	var oscript= document.createElement("script");
	oscript.type = "text/javascript";
	oscript.src = name;
	head.appendChild(oscript);	
}

动态加载css

//动态加载样式
function add_css(name) {
	var head = document.getElementsByTagName('head').item(0);
	var headlist = head.childNodes;
	for(var i = 0;i < headlist.length;i = i+1){
		if(headlist[i] != "" && headlist[i].type == "text/css"){
			if(headlist[i].href != null && headlist[i].href.indexOf(name) > -1){
				return;
			}
		}
	}
	var ocss = document.createElement("link");
	ocss.type = "text/css";
	ocss.rel = "stylesheet";
	ocss.href = name;
	head.appendChild(ocss);
}