在将元素附加到DOM之前,防止浏览器加载图像 [英] Prevent browser from loading image before attaching element to DOM

查看:667
本文介绍了在将元素附加到DOM之前,防止浏览器加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的思路是,浏览器不会尝试加载源代码,直到它连接到DOM,但是当我使用jQuery创建一个图像标签时,它会尝试在加载图像源之前附加它。在创建图像标签时,jQuery是否临时附加元素?



在此示例中,无效的URL会导致控制台中的错误日志,即使append命令已注释掉(查看jsFiddle )。

  $(document).ready(function(){
var $ img = $(< img>,{
height:100px
,width:100px
,src:http://content.com/bad.url.jpg
});
//$img.appendTo($(\"##容器));
});


解决方案

一旦他们的 src 被设置,图像开始加载图像文件(实时或从缓存),无论它们是否附加到DOM中的任何内容。请参阅: https://developer.mozilla.org/en/Canvas_tutorial/Using_images


My train of thought was that a browser wouldn't attempt to load a source until it was attached to the DOM, but when I use jQuery to create an image tag, it attempts to load the image source before I attach it. When creating the image tag, does jQuery temporarily attach the element?

In this example, the invalid URL causes a error log in the console, even with the append command commented out (view in jsFiddle).

    ​$(document).ready(function() {
    var $img = $("<img>", {
        height:"100px"
        ,width:"100px"
        ,src: "http://content.com/bad.url.jpg"
    });
    //$img.appendTo($("#container"));
});​

解决方案

Images start loading image files (either live or from cache) once their src is set, whether or not they are attached to anything in the DOM. See: https://developer.mozilla.org/en/Canvas_tutorial/Using_images

这篇关于在将元素附加到DOM之前,防止浏览器加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆