How to call a function after the document is ready and the image is loaded?

I used something like this:

$(document).ready(function() { $('#my-img').load(function() { // do something }); }); 

But sometimes he fails to complete the second callback (without any errors, so there is nothing to do there), and I think that maybe the image is loaded before the document is ready.

If I do not use the $ (document) .ready () part, it works fine, so I think I will leave it like that for now. But someone told me that it was good practice to always do things like call back a document because the document might not be ready. Is it correct?

Any thoughts?

+6
source share
2 answers

Adapted from download documentation ()

Download event warnings when used with images

The common problem developers are trying to solve with .load () is that the shortcut should function when the image (or image collection) is fully loaded. There are several well-known reservations with this to be noted. It:

It does not work consistently and not reliably, cross browser

WebKit does not work correctly if src is set to src, as before

Incorrectly inverts the DOM tree

**** May stop starting for images that are already in the browser cache ****

Especially the latter is a common problem.

You can try imagesLoaded plugin , but I got lucky with the following approach:

 var element = $('#my-img'); $("<img/>").load(function () { //create in memory image, and bind the load event //do something //var imageHeight = this.height; }).attr("src", element.attr("src")); //set the src of the in memory copy after binding the load event, to avoid WebKit issues 

This is dirty, but if you really need to perform some action after loading the image, this was the only reliable approach I was able to work with.

+13
source

An old question, but it can be useful for googlers: if you need to execute the code after loading the images and the images are in the DOM, you should use $ (window) .load instead of $ (document) .ready. How in:

 $(window).load(function() { console.log("My image is " + $('#my-img').width() + " pixels wide."); // You may not have known this before the image had loaded }); 

This is very important if you are doing any jiggerypokery with SVG or other inline documents.

+1
source

Source: https://habr.com/ru/post/897115/


All Articles