I just find an interest thing, when you change an element’s src, it’ll have several seconds delay and the line under it will execute before new picture rendered, so it’ll load latter picture’s size(width height) if you want to get the size immediately after change a picture’s src.
heres the evidence:
$("button").click(functon() { //set a button so you can handle the process.
var alert1 = $("#image").width(); //#image is an <img> element, don't set width and height.
var src = pictures.pop(); //pictures is an array which stored image base64 code.
$("#image").attr("src", src);
var alert2 = $("#image").width();
alert("alert1: " + alert1 + " alert2: " + alert2);
}
as the code shows, after it executed, the alert1 should show the width of the picture before change src, alert2 should show the width of picture after change src.
but what i actually see? both alert1 and alert2 all show the width of picure befor change src.
to enhance my opinion, there’s another exp:
$("button").click(functon() { //set a button so you can handle the process.
var alert1 = $("#image").width(); //#image is an <img> element, don't set width and height.
var src = pictures.pop(); //pictures is an array which stored image base64 code.
$("#image").attr("src", src);
alert("wait");
var alert2 = $("#image").width();
alert("alert1: " + alert1 + " alert2: " + alert2);
}
see? i add an alert box after change src so i can control the code to execute after change src, then what happened, the alert1 return the width of picture before change src and the alert2 return the width of picture after change src! so it’s proved that the process of src is done after the code after it executed.
What I want to know is why this happen, what happened when chrome change picture’s src?
ps: I just try this on chrome, if you are interested in this can do the same exp on other browdser.
This is probably because the image has not yet loaded. Why not put the code in the img’s
onloadevent? This way it will not fire until the image has completely loaded.