Recall window load event - javascript

前端 未结 1 784
情话喂你
情话喂你 2021-01-23 14:01

I am going to do my best here to distinctly explain what my issue is without the use of jsfiddle because $(window).on(\"load\") does not fire within their IDE.

相关标签:
1条回答
  • 2021-01-23 14:24

    The window's load event only executes once. Even when you dynamically add content, it will not be triggered. This behaviour is indeed different from ready(), where jQuery will call the callback always, even if the document is ready when it meets this code for the first time.

    When adding content dynamically there is no "one-liner" to get a callback run when all images of that content have been loaded. The code you would need to write, would have to capture the load event for every image you load, and see which one was last, also taking care of images that did not load (because of an invalid reference, or they were cached).

    The ImagesLoaded Plug-in provides a method that does all that. You can use it like this:

    $(function () {
        $(".content").load("screens/"+this.currentScreen+"/"+this.currentScreen + ".html .screen", function( response, status, xhr ) 
        {
            //other code 
            //
            //
            $(".content").imagesLoaded( function() {
                // images have loaded
                $(".content").toggleClass("hidden", false);
                $(".loader").toggleClass("hidden", true);
            });
        });
    });
    

    So I would suggest to just include that plug-in, like this:

    <script src="https://npmcdn.com/imagesloaded@4.1/imagesloaded.pkgd.min.js">
    </script>
    

    and use the imagesLoaded() method, like above code.

    0 讨论(0)
提交回复
热议问题