仅在不存在时加载jQuery

假设您要在整个页面上包含一个内容,并且其中包含您想要做一些jQuery特定的内容。 该页面可能已经加载jQuery,也可能尚未加载jQuery。 如果已经安装,则不想再次加载,但如果没有,则可以加载。 为此。

智能异步方式

// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {

	if (typeof $ == 'function') {
		// warning, global var
		thisPageUsingOtherJSLibrary = true;
	}
	
	function getScript(url, success) {
	
		var script     = document.createElement('script');
		     script.src = url;
		
		var head = document.getElementsByTagName('head')[0],
		done = false;
		
		// Attach handlers for all browsers
		script.onload = script.onreadystatechange = function() {
		
			if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
			
			done = true;
				
				// callback function provided as param
				success();
				
				script.onload = script.onreadystatechange = null;
				head.removeChild(script);
				
			};
		
		};
		
		head.appendChild(script);
	
	};
	
	getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function() {
	
		if (typeof jQuery=='undefined') {
		
			// Super failsafe - still somehow failed...
		
		} else {
		
			// jQuery loaded! Make sure to use .noConflict just in case
			fancyCode();
			
			if (thisPageUsingOtherJSLibrary) {

				// Run your jQuery Code

			} else {

				// Use .noConflict(), then run your jQuery Code

			}
		
		}
	
	});
	
} else { // jQuery was already loaded
	
	// Run your jQuery Code

};

注意,要运行get的jQuery代码在多个地方调用。 不要在那儿重复一遍,将它放在可以调用的函数中即可开始。

这段代码是从这里改编的。

Document.write方式

髋关节孩子不使用document.write,但是如果您年纪太大了,可以忽略以下内容:

var jQueryScriptOutputted = false;
function initJQuery() {
    
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
    
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
            //output the script (load it from google api)
            document.write("<scr" + "ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {
                        
        $(function() {  
            // do anything that needs to be done on document.ready
            // don't really need this dom ready thing if used in footer
        });
    }
            
}
initJQuery();

翻译自: https://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值