標籤:

jquery中img的load事件執行問題

最近在用jquery寫些小項目。本著用最新的版本,我就在bootcdn上引了最新的jquery版本

在頁面里有這麼一段代碼

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script> $(function () { var img=document.querySelector(img) img.onload=function () { alert(in jquery loaded) } })</script>

運行後,會發現這個alert根本執行。實際上用$(#img).on(load,function(){}),這種的方式,事件也是不執行的。

查資料,stackoverflow上有人指引到了這個api地址 jQuery API Documentation

這個資料里對img的load事件有以下說明

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

It doesnt work consistently nor reliably cross-browser

It doesnt fire correctly in WebKit if the image src is set to the same src as before

It doesnt correctly bubble up the DOM tree

Can cease to fire for images that already live in the browsers cache

img的load事件並不穩定。jquery 從緩存載入圖片,是不執行load事件的


如果在項目上,要判斷圖片載入顯示完成,我一直沒有想好實現方法。

用定時方法判斷img的complete狀態?

查stackoverflow,有推薦了一個插件:jQuery.imagesLoaded

jQuery callback on image load (even when the image is cached)stackoverflow.com圖標

這個問題下,其中一個回答者提供了解決方法

/** * Trigger a callback when the selected images are loaded: * @param {String} selector * @param {Function} callback */var onImgLoad = function(selector, callback){ $(selector).each(function(){ if (this.complete || /*for IE 10-*/ $(this).height() > 0) { callback.apply(this); } else { $(this).on(load, function(){ callback.apply(this); }); } });};/** * Trigger a callback when this image is loaded: * @param {Function} callback */(function($){ $.fn.imgLoad = function(callback) { return this.each(function() { if (callback) { if (this.complete || /*for IE 10-*/ $(this).height() > 0) { callback.apply(this); } else { $(this).on(load, function(){ callback.apply(this); }); } } }); };})(jQuery);

這兩個方法我還沒試過。

從這個問題下的回答來看,解決起來分兩種情況,如果圖片沒有載入過,則on load事件會執行,如果有緩存,那麼判斷complete再執行相關事件即可。

推薦閱讀:

前端日刊-2018.02.06
前端日刊-2017.12.23
【aux】統一現有的開發工具
《Oli-Zhao的前端一萬小時》之:做一次山大王,讓你的操作系統乖得像個小綿羊——命令行入門
前端日刊-2018.02.14

TAG:前端開發 |