Fade in images after they have loaded

后端 未结 6 1212
半阙折子戏
半阙折子戏 2020-12-13 00:58

I found this code to achieve the desired effect and tried it on JSFiddle

http://jsfiddle.net/AndyMP/7F9tY/366/

It seems to work in that it fades the image in

6条回答
  •  独厮守ぢ
    2020-12-13 01:48

    The only reliable way to fadeIn() an image that is in your actual HTML markup is to set an onload handler in the HTML markup like this:

    Working demo here: https://jsfiddle.net/jfriend00/X82zY/

    Doing is this way, you don't need to give each image an id or class. Just set the style and the event handler in the markup.

    The reason you have to put the event handler in the markup is that if you wait until your page's javascript runs, it may be too late. The image may already be loaded (particularly if it's in the browser cache) and thus you may have missed the onload event. If you put the handler in the HTML markup, you will not miss the onload event because the handler is assigned before the image starts loading.

    If you don't want to put event handlers in the javascript, then you can do something like this where you use a placeholder for the image in the actual HTML and you use javascript to create the actual image tags and insert them and pull the image URL from the placeholder:

    Working demo: https://jsfiddle.net/jfriend00/BNFqM/

    The first option will get your images loaded a little quicker (because image loading starts immediately upon page parsing), but the second option gives you more programmatic control over the process.

提交回复
热议问题