解决方法
对窗口使用
load()
(docs)方法。
- $(window).load(function() {
- // this will fire after the entire page is loaded,including images
- });
或者直接通过window.onload
。
- window.onload = function() {
- // this will fire after the entire page is loaded,including images
- };
如果您想要为每个图像触发单独的事件,请在每个图像上放置一个.load()。
- $(function() {
- $('img').one('load',function() {
- // fire when image loads
- });
- });
或者如果有可能缓存图片,请执行以下操作:
- $(function() {
- function imageLoaded() {
- // function to invoke for loaded image
- }
- $('img').each(function() {
- if( this.complete ) {
- imageLoaded.call( this );
- } else {
- $(this).one('load',imageLoaded);
- }
- });
- });
编辑:
为了在最后一个图像加载后执行一些操作,请使用在图像总数设置的计数器,并在每次调用加载处理程序时递减计数。
当它达到0时,运行一些其他代码。
- $(function() {
- function imageLoaded() {
- // function to invoke for loaded image
- // decrement the counter
- counter--;
- if( counter === 0 ) {
- // counter is 0 which means the last
- // one loaded,so do something else
- }
- }
- var images = $('img');
- var counter = images.length; // initialize the counter
- images.each(function() {
- if( this.complete ) {
- imageLoaded.call( this );
- } else {
- $(this).one('load',imageLoaded);
- }
- });
- });