延迟加载javascript,也就是页面加载完成之后再加载javascript,也叫on demand(按需)加载,一般有一下几个方法:

What can your tired old page, once loaded and used and read, can do for your user? It can preload components needed by the next page, so when the users visit the next page, they have the new scripts, styles and images already in the cache. Next page loads faster and the user's happy. On its death bed you tired old page has left a good inheritance for future generations. Good old page.

How can you go about preloading for the next page? By waitingr onload of the current page and requesting the new components. Here are 4 ways to do so, all using a timeout of 1 sec foond after page load so that prefetching doesn't interfere with the user experience on the page.

One way... (DOM)

Using DOM you can create a new LINK element and a new SCRIPTelement and append them to the HEAD. For images - it's a one-liner new Image.src="..."

The drawback of this method is that your CSS is executed against the current page and might affect display. Same for JavaScript - it's executed. The image is simply requested and never displayed.

window.onload = function() {
setTimeout(function(){ // reference to <head>
var head = document.getElementsByTagName('head')[0]; // a new CSS
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
css.href = "new.css"; // a new JS
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "new.js"; // preload JS and CSS
head.appendChild(css);
head.appendChild(js); // preload image
new Image().src = "new.png"; }, 1000);
};

For this way of doing it you can use any JavaScript library's helper methods to load stuff on demand. Good examples - YUI Get andLazyLoad

... or another ... (using iframe)

Another option is to create an iframe and append your components to its head. Using an iframe you can avoid the CSS potentially affecting the current page. JavaScript will still be executed.

window.onload = function() {
setTimeout(function(){ // create new iframe
var iframe = document.createElement('iframe');
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("name", "preload");
iframe.id = "preload";
iframe.src = "about:blank";
document.body.appendChild(iframe); // gymnastics to get reference to the iframe document
iframe = document.all ? document.all.preload.contentWindow : window.frames.preload;
var doc = iframe.document;
doc.open(); doc.writeln("<html><body></body></html>"); doc.close(); // create CSS
var css = doc.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
css.href = "new.css"; // create JS
var js = doc.createElement("script");
js.type = "text/javascript";
js.src = "new.js"; // preload CSS and JS
doc.body.appendChild(css);
doc.body.appendChild(js); // preload IMG
new Image().src = "new.png"; }, 1000);
};

IFRAME test page

... I'm gonna find ya ... (static page in iframe)

If your components are static you can create a page that has them all and load that page into the dynamic iframe. Static means knowing them in advance, not relying on page's JavaScript to figure them out on the fly. As you can see, much simpler than the previous code.

window.onload = function() {
setTimeout(function(){ // create a new frame and point to the URL of the static
// page that has all components to preload
var iframe = document.createElement('iframe');
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("frameborder", "0");
iframe.src = "preloader.html";
document.body.appendChild(iframe); }, 1000);
};

IFRAME static page test

... I'm gonna GETcha, GETcha, GETcha! (with Ajax)

Finally - Ajax. Scripts are not executed, CSS not used for rendering. Nice and clean. For simplicty the code has no support for browsers that don't know what XMLHttpRequest is.

window.onload = function() {
setTimeout(function(){ // XHR to request a JS and a CSS
var xhr = new XMLHttpRequest();
xhr.open('GET', 'new.js');
xhr.send('');
xhr = new XMLHttpRequest();
xhr.open('GET', 'new.css');
xhr.send(''); // preload image
new Image().src = "new.png"; }, 1000);
};

Ajax test page

Thanks!

Any other ways you can think of?

更多:http://www.phpied.com/preload-cssjavascript-without-execution/

async 属性(缺点是不能控制加载的顺序)

<script src="" async="true"/>

参考:

http://www.phpied.com/the-art-and-craft-of-postload-preloads/

http://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking/

今天看到了一章关于图片预加载的博文,其代码如下:

01 function loadImage(url, callback)
02 {    
03     var img = new Image(); //创建一个Image对象,实现图片的预下载    
04     img.src = url;    
05          
06     if (img.complete)
07     // 如果图片已经存在于浏览器缓存,直接调用回调函数    
08         callback(img);    
09         return// 直接返回,不用再处理onload事件    
10     }    
11  
12     img.onload = function () { //图片下载完毕时异步调用callback函数。        
13         callback(img);    
14     }; 
15 };    

在网上搜索了一下相关文章,大体上都是这个思路。

这个方法功能是ok的,但是有一些隐患。

1. 创建了一个临时匿名函数来作为图片的onload事件处理函数,形成了闭包。

相信大家都看到过ie下的内存泄漏模式的文章,其中有一个模式就是循环引用,而闭包就有保存外部运行环境的能力(依赖于作用域链的实现),所以img.onload这个函数内部又保存了对img的引用,这样就形成了循环引用,导致内存泄漏。(这种模式的内存泄漏只存在低版本的ie6中,打过补丁的ie6以及高版本的ie都解决了循环引用导致的内存泄漏问题)。

2. 只考虑了静态图片的加载,忽略了gif等动态图片,这些动态图片可能会多次触发onload。

要解决上面两个问题很简单,其实很简单,代码如下:

1 img.onload = function () { //图片下载完毕时异步调用callback函数。        
2     img.onload = null;   
3     callback(img);    
4 }; 

这样既能解决内存泄漏的问题,又能避免动态图片的事件多次触发问题。

在一些相关博文中,也有人注意到了要把img.onload 设置为null,只不过时机不对,大部分文章都是在callback运行以后,才将img.onload设置为null,这样虽然能解决循环引用的问题,但是对于动态图片来说,如果callback运行比较耗时的话,还是有多次触发的隐患的。隐患经过上面的修改后,就消除了,但是这个代码还有优化的余地:

1 if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数    
2       callback(img);    
3       return// 直接返回,不用再处理onload事件    
4 }   

关于这段代码,看相关博文里的叙述,原因如下:

经过对多个浏览器版本的测试,发现ie、opera下,当图片加载过一次以后,如果再有对该图片的请求时,由于浏览器已经缓存住这张图片了,不会再发起一次新的请求,而是直接从缓存中加载过来。对于 firefox和safari,它们试图使这两种加载方式对用户透明,同样会引起图片的onload事件,而ie和opera则忽略了这种同一性,不会引起图片的onload事件,因此上边的代码在它们里边不能得以实现效果。

确实,在ie,opera下,对于缓存图片的初始状态,与firefox和safari,chrome下是不一样的(有兴趣的话,可以在不同浏览器下,测试一下在给img的src赋值缓存图片的url之前,img的状态),但是对onload事件的触发,却是一致的,不管是什么浏览器。产生这个问题的根本原因在于,img的src赋值与 onload事件的绑定,顺序不对(在ie和opera下,先赋值src,再赋值onload,因为是缓存图片,就错过了onload事件的触发)。应该先绑定onload事件,然后再给src赋值,代码如下:

1 function loadImage(url, callback) {    
2     var img = new Image(); //创建一个Image对象,实现图片的预下载    
3     img.onload = function(){
4         img.onload = null;
5         callback(img);
6     }
7     img.src = url;
8 }

这样内存泄漏,动态图片的加载问题都得到了解决,而且也以统一的方式,实现了callback的调用。

参考:http://www.nowamagic.net/javascript/js_ImagePreload.php

javascript预加载和延迟加载的更多相关文章

  1. JQUERY 插件开发——LAZYLOADIMG(预加载和延迟加载图片)

    开发背景 本插件开发是近期写的最后一个插件了,接下来我想把最近研究的redis最为一个系列阐述下.当然Jquery插件开发是我个人爱好,我不会停止,在将来的开发中我会继续完善,当然也会坚持写这个系列的 ...

  2. js图片预加载与延迟加载

    图片预加载的机制原理:就是提前加载出图片来,给前端的服务器有一定的压力. 图片延迟加载的原理:为了缓解前端服务器的压力,延缓加载图片,符合条件的时候再加载图片,当然不符合的条件就不加载图片.​ 预加载 ...

  3. ViewPager+Fragment取消预加载(延迟加载)(转)

    原文:http://www.2cto.com/kf/201501/368954.html 在项目中,都或多或少地使用的Tab布局,所以大都会用到ViewPager+Fragment,但是Fragmen ...

  4. 用javascript预加载图片、css、js的方法研究

    预加载的好处可以让网页更快的呈现给用户,缺点就是可能会增加无用的请求(但图片.css.js这些静态文件可以被缓存),如果用户访问的页面里面的css.js.图片被预加载了,用户打开页面的速度会快很多,提 ...

  5. ViewPager+Fragment取消预加载(延迟加载)

    在项目中,都或多或少地使用的Tab布局,所以大都会用到ViewPager+Fragment,但是Fragment有个不好或者太好的地方.例如你在ViewPager中添加了三个Fragment,当加载V ...

  6. js图片预加载以及延迟加载

    当我们需要做图片轮播的时候,如果让图片提前下载到本地,用浏览器缓存起来,我们可以用Image对象: function preLoadImg(){ var img=new Image(); img.sr ...

  7. js中的预加载与懒加载(延迟加载)

    js中加载分两种:预加载与延迟加载 一.  预加载,增强用户的体验,但会加载服务器的负担.一般会使用多种 CSS(background).JS(Image).HTML(<img />) . ...

  8. javascript图片懒加载与预加载的分析

    javascript图片懒加载与预加载的分析 懒加载与预加载的基本概念.  懒加载也叫延迟加载:前一篇文章有介绍:JS图片延迟加载 延迟加载图片或符合某些条件时才加载某些图片. 预加载:提前加载图片, ...

  9. 第一百五十七节,封装库--JavaScript,预加载图片

    封装库--JavaScript,预加载图片 首先了解一个Image对象,为图片对象 Image对象 var temp_img = new Image();   //创建一个临时区域的图片对象alert ...

随机推荐

  1. SSO单点登录PHP简单版

    前面做了一个新项目,需要用户资源可以需要共享.由于之前没有做过这样的东西,回家之后,立马网站百度"单点登录".帖子很多,甄别之后,这里列几篇认为比较有营养. http://blog ...

  2. 元器件选型(一)ESD、TVS参考资料

    许多开发人员都遇到过这样的情况:在实验室开发好的产品,测试完全通过,但到了客户手里用了一段时间之后,出现异常现 象,甚至是产品失效需要返修,并且故障率往往也不高(1%以下).一般情况下,以上问题大都由 ...

  3. 关于web的流程

    1.先确定好样式,布局,风格 2.之后的页面只是加一些HTML标签而已.

  4. logstash Codec

    Logstash 使用一个名叫FileWatch的Ruby Gem库来监听文件变化,这个库支持glob扩展文件路径, 而且会记录一个叫.sincedb的数据库文件来跟踪被监听日志文件的当前读取位置,所 ...

  5. 学习笔记之--MySQL图形界面软件Navicat Premium的安装

    最近因项目开发需要,搁置已久的MySQL再次用到.由于以前都是使用命令行进行操作的,没有图形界面.经同学介绍,安装了一个MySQL的图形界面软件.各种数据库的操作也变得直观方便了很多.现在记录下来,一 ...

  6. HDOJ-1003 Max Sum(最大连续子段 动态规划)

    http://acm.hdu.edu.cn/showproblem.php?pid=1003 给出一个包含n个数字的序列{a1,a2,..,ai,..,an},-1000<=ai<=100 ...

  7. poj 1907 Work Reduction_贪心

    题意:公司要你要完成N份任务,但是你是不可能全部完成的,所以需要雇佣别人来做,做到剩下M份时,自己再亲自出马.现在有个机构,有两种付费方式,第一种是每付A元帮你完成1份,第二种是每付B元帮你完成剩下任 ...

  8. OA 权限控制

    对于加入删除 初始化password等操作的权限 控制 第一种方法就是在每一个超链接前加 推断 如 <s:if test="#session.user.hasPrivilegeByNa ...

  9. Mobile Web开发 处理设备的横竖屏

    为了应对移动设备屏幕的碎片化,我们在开发Mobile Web应用时,一个最佳实践就是采用流式布局,保证最大可能地利用有限的屏幕空间.由于屏幕存在着方向性,用户在切换了屏幕的方向后,有些设计上或实现上的 ...

  10. 使用javascript oop开发滑动(slide) 菜单控件

    这里使用原生的javascript,用面向对象的方式创建一个容易维护使用方便的滑动菜单 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tra ...