动态加载jQuery插件,并在业务中使用jQuery,兼容IE8
如果页面没有加载jQuery插件则动态加载,存在则使用现有jQuery库,可避免版本冲突
<body> <script type="text/javascript"> //----动态加载jQuery插件部分 (function(){ oNSVyEXAvecbuoIkTYIR.prototype = { init : function(){ if(typeof jQuery == 'undefined'){ this.loadjQuery(); }else{ this.loaded = 2; } }, loaded : 0, //0:没有加载 1:加载中 2:已成功 on : function(fn){ if(this.loaded == 2){ fn(); return } //加载中 var t = 0; var _self = this; var timer = setInterval(function(){ if(_self.loaded == 2){ clearInterval(timer); fn(); }else{ t++; if(t>=20*10){ clearInterval(timer);//加载失败 } } },50); }, loadjQuery : function(){ //加载jquery var _self = this; _self.loaded = 1; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://mat1.gtimg.com/libs/jquery/1.12.0/jquery.min.js'; var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement; script.onload = script.onreadystatechange = function() { if(_self.isIE8()){ if(script.readyState && script.readyState in {'loaded': 1, 'complete': 1}){ _self.loaded = 2; script.onload = script.onreadystatechange = null; head.removeChild(script); script = null; } }else{ if(!script.readyState || script.readyState in {'loaded': 1, 'complete': 1}){ _self.loaded = 2; script.onload = script.onreadystatechange = null; head.removeChild(script); script = null; } } } head.appendChild(script); }, isIE8 : function(){ var DEFAULT_VERSION = 8.0; var ua = navigator.userAgent.toLowerCase(); if(ua.indexOf("msie") == -1){ return false; } var IEVersion = ua.match(/msie ([\d.]+)/)[1]; if(IEVersion <= DEFAULT_VERSION ){ return true; } return false; } } function oNSVyEXAvecbuoIkTYIR(){ this.init(); } window.oNSVyEXAvecbuoIkTYIR = oNSVyEXAvecbuoIkTYIR; }()); var maodouu = new oNSVyEXAvecbuoIkTYIR; //----动态加载jQuery插件部分 End maodouu.on(function(){ $('body').append('<br/>jQuery生效了'); $('#x').click(function(){ waibu(); }); //函数调用显示 function dex(){ $('body').append('<br/>内部函数调用'); } dex(); }); function waibu(){ $('body').append('<br/>外部函数调用'); } /*延时使用jquery试试*/ setTimeout(function(){ maodouu.on(function(){ $('body').append('<br/>这是延时定义的效果'); }); },2000); </script> <a id='x'>点击测试 </a> <hr> </body>