动态加载js

1、每个页面引入文件:init.js

function loadJs(jsFiles){
	var jsFile, defaultJsFiles=[global_path+'/resources/js/phone/zepto.min.js',global_path+'/resources/js/phone/common.js'];
	if(jsFiles){
		defaultJsFiles = jsFiles;
	}
	if(defaultJsFiles.length==0){
		return;
	}
	jsFile = defaultJsFiles.shift();
	var script, head  = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
		script = document.createElement( "script" );
		script.charset = "utf-8";
		script.src = jsFile;
		script.onload = script.onreadystatechange = function() {
			if (!this.readyState || /loaded|complete/.test( this.readyState ) ) {
				this.onload = this.onreadystatechange = null;
				script = undefined;
			}
			loadJs(defaultJsFiles);
		};
		head.insertBefore( script, head.firstChild );
}
loadJs();

 2、common.js

//初始化
$(function(){
	toggleNav();
});
//隐藏底部菜单
function toggleNav(){
	$("input,textarea").each(function(){
		$(this).bind("focus",function(){
			if($("#all_b_menu").length>0){
				$("#all_b_menu").css({"display":"none"});
			}
		});
		$(this).bind("blur",function(){
			if($("#all_b_menu").length>0){
				$("#all_b_menu").css({"display":"block"});
			}
		});
	});
}

 3、要点

为什么要用递归?

因为动态引入的两个js文件有依赖关系,而且js文件的加载时异步的,所以需要等待基类资源加载完再加载后面的文件,不然找不到依赖的函数。

你可能感兴趣的:(js)