简体   繁体   English

不要在隐藏元素中加载图像

[英]Don't load images within hidden elements

This is not a duplicate of this because it also uses the document.ready approach which obviously does not work. 不是重复 这个 ,因为它也使用document.ready的做法,显然是行不通的。

I want to avoid that the browser loads images ( <img> ) nested within hidden <div> elements. 我想避免浏览器加载嵌套在隐藏的<div>元素中的图像( <img> )。

So I tried this, however the javascript gets executed too late, the browser already starts to download images that it shouldn't. 所以我尝试了这个,但是javascript执行得太迟了,浏览器已经开始下载不应该的图像了。

  $(document).ready(function() {
    $('div').not(":visible").each(function () {
       $(this).find('img').each(function() {
         $(this).attr("src","");
       });
    });
  });

Is there a good javascript solution for this? 有一个很好的JavaScript解决方案吗? Or do I have to use <img srctmp="...."/> and then replace srctmp by src via javascript for those images which are NOT nested within a hidden <div> ? 或者我是否必须使用<img srctmp="...."/>然后通过javascript将srctmp替换为src ,以便那些未嵌套在隐藏的<div>

You can use a data attribute instead the src , browser loads images only form src , so you can start with data-src for every images and then add the src only to the visible ones. 您可以使用data属性而不是src ,浏览器仅从src加载图像,因此您可以从每个图像的data-src开始,然后仅将src添加到可见的图像。

HTML: HTML:

  <img data-src="path/to/image.jpg" />

JS: JS:

  $(document).ready(function() {
    $('div').is(":visible").each(function () {
       $(this).find('img').each(function() {
         $(this).attr("src", $(this).data("src"));
       });
    });
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM