我注意到当我做这样的事情时(使用 jQuery,但我认为这并不重要):
$("#myDiv").html("<img src='/image.png'/> this is my image.");
浏览器首先显示文本,然后加载图像,并将文本向右移动,从而产生可怕的闪烁效果。
浏览器似乎没有缓存该图像。知道为什么吗?将图像加载到 DOM 时如何避免这种现象?
最佳答案
How can I avoid this phenomena when loading images into the DOM ?
主要有两种方法(可能更多:))
1) 设置img的实际大小<img with='20' height='20' src='...' />
或通过 CSS 样式。
2) 使用图像预加载并仅在加载图像时插入代码
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:SO引擎中有一个严重的包——代码格式化不想与编号列表结合。所以我删除了该列表。
关于javascript - 插入 DOM 时图像闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9169359/