最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Image flickering when inserted into the DOM - Stack Overflow

programmeradmin3浏览0评论

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 ?

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 ?

Share Improve this question asked Feb 7, 2012 at 0:21 BlacksadBlacksad 15.5k16 gold badges74 silver badges81 bronze badges 2
  • Flickering effect? Could you explain or demonstrate? I don't see flickering in my demo: jsfiddle/nsbmW – Šime Vidas Commented Feb 7, 2012 at 0:34
  • @ŠimeVidas The flickering might appear at slow connections and large image files. – Cheery Commented Feb 7, 2012 at 0:45
Add a ment  | 

4 Answers 4

Reset to default 5

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 bine with numbered listing. So I removed the list.

Preload the image before attaching it:

$("<img>", {
    load: function() {
        $("#myDiv").empty().append( this, "this is my image." );
    },
    src: "/image.png"
});

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);
});

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.

发布评论

评论列表(0)

  1. 暂无评论