简体   繁体   English

jQuery负载并非总是触发 <picture> Chrome中的元素

[英]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. 我正在使用元素将响应性图像与picturefill polyfill一起用于不受支持的浏览器。 Everything works fine even in the unsupported browsers. 即使在不受支持的浏览器中,一切都可以正常工作。 But in chrome, where it is supported, my jquery load event isnt consistently firing. 但是在支持Chrome的Chrome中,我的jquery加载事件未持续触发。 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? 关于我可以做什么使其在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. 即使将setTimeout设置为0也可以,但为了节省,我给了它10ms。 Ive experienced a few scenarios before where a small timeout solves the problem with chrome. Ive经历了一些情况,在此之前一个小的超时可以解决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. 我的猜测是,有时会在设置侦听器之前触发load事件。 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. 为了解决这个问题,您可以使用捕获事件侦听器,尽管旧版本的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();" 如果您需要支持旧版IE,则可以使用onload="mainSlider.init();" on the img or maybe $(document).ready(mainSlider.init) . img$(document).ready(mainSlider.init)

Note that you can get multiple load events on an img when using srcset or picture (when the image changes). 请注意,使用srcsetpicture (当图像更改时),可以在img上获得多个load事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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