有没有办法在显示器内制作图像:没有被浏览器下载?

时间:2012-04-04 01:44:38

标签: javascript jquery html css

我希望浏览器(特别是移动webkit)不要下载display:none div内的图像。现在,它们被下载而不是渲染。

是否有jquery插件可以执行此操作?

2 个答案:

答案 0 :(得分:3)

您可以使用data-*属性。这样,您可以让jQuery按需加载它们:

<img data-source="image_path">

//this one gets all images and loads them
$('img').each(function(){
    //loads the source from data-source
    this.src = this.getAttribute('data-source');
});

<img data-source="image_path" class="foo">
<img data-source="image_path" class="foo">

//this one gets all images that have class foo and loads them
$('img.foo').each(function(){
    //loads the source from data-source
    this.src = this.getAttribute('data-source');
});

当然,您需要将其包装在一个函数中,以便您可以根据需要调用哪些图像。像:

function loadImg(selector){
    $(selector).each(function(){
        this.src = this.getAttribute('data-source');
    });
}

//load images with class foo:
loadImg('.foo');

答案 1 :(得分:0)

我不这么认为。可以肯定的是,您需要原始的HTML DOM来排除隐藏的图像,您可以使用基于用户代理嗅探的服务器端编程(尽管不建议这样做)。在document.readydocument.load之后修改DOM意味着浏览器已经有机会从服务器请求资产,即使它们可能不会显示。

这很不寻常,但如果你仍然想使用jQuery,你可以按照@Pointy的建议,将所有图像占位符放在你的标记中。然后使用属性作为数据源,将:visible占位符替换为所需的图像。不需要插件,只需使用replaceWith()attr()之类的内容替换您要下载的图片的占位符节点,或更改src属性。

我会使用1x1透明gif作为占位符,具有正确的高度和宽度属性,而不是占位符没有源<img>。这样,当页面呈现时页面流将被正确确定,因此当图像延迟加载时它不会跳转。

相关问题