为了实现让js尽可能快的下载,而又不马上执行,想到了这么一个方法:先想方设法提前加载资源,在需要使用的时候再利用<script>标签引入资源。
实现步骤:
一、在head标签中:
折叠展开C/C++ Code复制内容到剪贴板
- <script type="text/javascript">
-
- (function() {
-
- window.preLoad=function(url,fn){
- var c,fg,h,ua,dh;
- if(!url) return;
- ua=navigator.userAgent;
- fg=ua.indexOf("Chrome")>-1||ua.indexOf("Safari")>-1?true:false;
-
- dh=function(){
- setTimeout(function(){
- h();
- },1500);
- };
-
- if(fg){
- c=new Image();
- h=function(){
- c=null;
- if(typeof(fn)=="function"){fn();}
- };
- if(c.onload || c.onerror){
- c.onload=h;
- c.onerror=h;
- }else{
- dh();
- }
- c.src = url;
- }else{
- c = document.createElement('link');
- c.rel="stylesheet";
- c.media="print";
- h=function(){
- document.getElementsByTagName('head')[0].removeChild(c);
- c=null;
- if(typeof(fn)=="function"){fn();}
- };
- if(c.onload || c.onerror){
- c.onload=h;
- c.onerror=h;
- }else{
- dh();
- }
- document.getElementsByTagName('head')[0].appendChild(c);
- c.href = url;
- }
- };
-
-
- var url="http://jsnewt.sohu.com/j-src/Package.js";
- preLoad._ready=[0];
- preLoad(url,function(){
- preLoad._ready.push(function(){
- var s = document.createElement('script');
- s.src = url;
- s.type = 'text/javascript';
- document.getElementsByTagName('head')[0].appendChild(s);
- s = null;
- });
- if(preLoad._ready[0]==1){
- preLoad._ready[1].apply();
- }else{
- preLoad._ready[0]=1;
- }
- });
-
- })();
-
- </script>
-
- 二、在</body>标签前:
-
- <script type="text/javascript">
-
-
- if(preLoad && preLoad._ready){
- if(preLoad._ready.length==2){
- preLoad._ready[1].apply();
- }else{
- preLoad._ready[0]=1;
- }
- }
-
- </script>