简体   繁体   中英

Javascript - detect when image loaded

I have a function that, among other things, grabs a data attribute from an element and uses it for some calculations. The problem is that the attribute is assigned only once the element's background image has loaded.

Since the function is firing before the background image has loaded, the variable I'm looking for is undefined (and therefore causing other issues). I thought I would fix that by having a while loop for when the variable is undefined. If that variable is undefined, keep checking for it until it's not:

while ($(".element").data("ui-color") == "undefined"){
    var color = "" // keep it blank until the attribute exists
}

Then once after the loop is no longer true, assign the variable:

var color = $(".element").data("ui-color");

The problem is that it seems to be disregarding the while loop and still resulting in an undefined variable.

Is there some other condition I should be using for the while loop (or some other method completely)?

You should use JavaScript's Image.onload event, and execute the loop once the image has loaded.

Example:

var img = new Image;
img.onload = function() {
  // your calculations here
}
img.src = 'path/to/file';

The onload event will fire once the image is fully downloaded and displayed by the browser.

Try to see in a different way, use on load event on the background image. like

$("#background").on("load",function() { console.log("blah") }

EDIT: this doesn't actually solve the problem, but instead identifies an error in the code

Make this change for your code to work

typeof $(".element").data("ui-color") == "undefined"

The typeof operator will evaluate the left-hand side to the string literal 'undefined' which is what looks like you intended to do.

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