最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Preloading images in HTML - Stack Overflow

programmeradmin1浏览0评论

I want to preload these 4 images. I tried this:

<img src="img/1.jpg" style="display:none">
<img src="img/1a.jpg" style="display:none">
<img src="img/1b.jpg" style="display:none">
<img src="img/1c.jpg" style="display:none">

It didn't work so I tried this instead:

new Image().src = "img/1.jpg";
new Image().src = "img/1a.jpg";
new Image().src = "img/1b.jpg";
new Image().src = "img/1c.jpg";

The JS method worked with the background but not with these.

I want to preload these 4 images. I tried this:

<img src="img/1.jpg" style="display:none">
<img src="img/1a.jpg" style="display:none">
<img src="img/1b.jpg" style="display:none">
<img src="img/1c.jpg" style="display:none">

It didn't work so I tried this instead:

new Image().src = "img/1.jpg";
new Image().src = "img/1a.jpg";
new Image().src = "img/1b.jpg";
new Image().src = "img/1c.jpg";

The JS method worked with the background but not with these.

Share edited Mar 14, 2015 at 3:13 Nathan Tuggy 2,24427 gold badges32 silver badges38 bronze badges asked Mar 14, 2015 at 2:42 mrpinkmanmrpinkman 2115 silver badges14 bronze badges 5
  • 2 Can describe "preloading" ? – guest271314 Commented Mar 14, 2015 at 2:59
  • 1 @guest271314: Presumably, loading when the page does but without initially being displayed, to avoid latency later when they are shown. – Nathan Tuggy Commented Mar 14, 2015 at 3:10
  • @NathanTuggy Yes . Not certain if "preloading" at window , document , or other parent element load event ? , not included at OP ? – guest271314 Commented Mar 14, 2015 at 3:13
  • @guest271314: While the exact timing is certainly useful to know, I'm not sure it's crucial. – Nathan Tuggy Commented Mar 14, 2015 at 3:13
  • What are you planning to do with the images? That my influence the solution. Also what makes you think what you have tries is not working, as from what I can tell, they should. – Jon P Commented Mar 14, 2015 at 3:19
Add a ment  | 

4 Answers 4

Reset to default 3

Try utilizing $.Deferred() , .queue()

var images = ["http://lorempixel./1200/800/cats/"
             , "http://lorempixel./1200/800/nature/"
             , "http://lorempixel./1200/800/animals/"
             , "http://lorempixel./1200/800/technics/"
             ];
    // do stuff when image loaded
    var loadImage = function loadImage(elem) {
      return $(elem).fadeTo(500, "1.0", "linear"); 
    };
    
    // load images
    var loadImages = function loadImages(urls, image, plete) {
        // `this` : `document`
        urls.forEach(function(imageSrc, i) {
          var img = new Image;
          var dfd = new $.Deferred();
          // return `this` : `document`
          dfd.then(function(ready) {
              loadImage(ready);   
              return this
          }, function(error) {
             console.log(error)
          })
          .always(function() {
             console.log(plete, urls.length);
             return urls.length === plete 
                    ? $(this)
                      .data("plete", plete + " images loaded")
                      .dequeue("images") // when all images loaded
                    : this
    
          });
          // log errors
          img.onerror = dfd.reject;
          img.onload = function(e) {
            plete = this.plete ? ++plete : plete;
            dfd.resolveWith(document, [
              image.eq(i).prop("src", this.src)
              ]
            );
    
          };
          img.src = imageSrc
          });
          // return `this` : `document`
          return this
    };
    

    $(window).load(function() {
        // init `loadImages`
        var plete = 0;
        // call `loadImages`,
        // `this` context : `document` 
        loadImages.call(document, images, $(".image"), plete)
    
    });
    
    $(document).ready(function() {
        // notify when all images loaded
        $(this).queue("images", function() {
          console.log($(this).data())
        });               
    });
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<!-- note , `src` attribute not included -->
<img class="image" style="opacity:0.0" alt="1">
<img class="image" style="opacity:0.0" alt="1a">
<img class="image" style="opacity:0.0" alt="1b">
<img class="image" style="opacity:0.0" alt="1c">

This never actually appends anything to the DOM, I used an array to keep references of the created images, and pass them to an optional callback

var paths =  [
    "img/1.jpg",
    "img/1a.jpg",
    "img/1b.jpg",
    "img/1c.jpg"
];

preloadImages(paths);

function preloadImages(paths, callback) {
    var images = [];
    var loaded = 0;

    paths.forEach(function (path) {
        var img = new Image();
        img.src = path;
        img.onload = onImagePreloaded;
        images.push(img);
    });


    function onImagePreloaded() {
        loaded++;
        if (loaded === paths.length && callback) {
             callback(images);
        }
    }
}

Instead of setting the images themselves to display: none;, set it on the container.

CSS:

.preload {
    display: none;
}

HTML:

<div class="preload">
    <img src="img/1.jpg">
    <img src="img/1a.jpg">
    <img src="img/1b.jpg">
    <img src="img/1c.jpg">
</div>

You can simply use a link tag in your head:

<head>
  <link rel="preload" href="example.png" as="image">
</head>

MDN Documentation

发布评论

评论列表(0)

  1. 暂无评论