简体   繁体   中英

jQuery load not always firing with <picture> element in Chrome

I'm using the element for responsive images with the picturefill polyfill for unsupported browsers. Everything works fine even in the unsupported browsers. But in chrome, where it is supported, my jquery load event isnt consistently firing. Heres my code:

$("#banner .banner-slide a img").load(mainSlider.init)

And my picture element:

<picture>
    <!--[if IE 9]><video style="display: none;"><![endif]-->
    <source srcset="http://placehold.it/1920x300" media="(min-width: 1440px)" />
    <source srcset="http://placehold.it/1440x300" media="(min-width: 1024px)" />
    <source srcset="http://placehold.it/1024x250" media="(min-width: 640px)" />
    <source srcset="http://placehold.it/640x150" media="(min-width: 481px)" />
    <source srcset="http://placehold.it/480x150" media="(max-width: 480px)" />
    <!--[if IE 9]></video><![endif]-->
    <img srcset="http://placehold.it/1440x300" alt="" />
</picture>

Any idea as to what i can do to get it to work properly in chrome?

Fixed

Not too sure what the deal was but adding the below the load listener fixed it. Even with a setTimeout of 0 worked but to be save i gave it 10ms. Ive experienced a few scenarios before where a small timeout solves the problem with chrome.

//Fix chrome bug
setTimeout(function () {
    $(window).resize();
}, 10)

My guess is that sometimes the load event is fired before the listener is set up. Then you miss the event and nothing happens. This can happen in any browser.

To solve this you could use a capturing event listener, although that is not supported in old versions of IE.

document.addEventListener('load', function(e) {
    if (e.target === $("#banner .banner-slide a img")[0]) {
        mainSlider.init();
    }
}, true);

If you need to support old IE then you can use onload="mainSlider.init();" on the img or maybe $(document).ready(mainSlider.init) .

Note that you can get multiple load events on an img when using srcset or picture (when the image changes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM