Reputation: 15422
I noticed that when I do something like this (with jQuery, but I don't think it matters):
$("#myDiv").html("<img src='/image.png'/> this is my image.");
The browser displays the text first, and then the image is loaded, and shifts the text to the right which creates a horrible flickering effect.
The image doesn't appear to be cached by the browser. Any idea why ? How can I avoid this phenomena when loading images into the DOM ?
Upvotes: 2
Views: 2217
Reputation: 16214
How can I avoid this phenomena when loading images into the DOM ?
there are two major methods (may be more :))
1) Set the actual size of the img <img with='20' height='20' src='...' />
or via CSS style.
2) Use image preload and insert your code only when image is loaded
var img = new Image();
$(img).load(function(){
$("#myDiv").append($(this))
.append(document.createTextNode("this is my image.");
// or your way, browser should take image from cache
$("#myDiv").append("<img src='/image.png'/> this is my image.");
}).attr('src', '/image.png');
ps: there is a serious bag in SO engine - code formatting does not want to combine with numbered listing. So I removed the list.
Upvotes: 5
Reputation: 2750
preload your images like this
var images = [
'/path/to/some/image1.png',
'/path/to/some/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
Upvotes: 1
Reputation: 140230
Preload the image before attaching it:
$("<img>", {
load: function() {
$("#myDiv").empty().append( this, "this is my image." );
},
src: "/image.png"
});
Upvotes: 1
Reputation: 942
Images may render a little slower that text, even if cached. If you know the dimensions of the image add height
and width
attributes to the image and then it won't jump around.
Upvotes: 0