Controlling image load order in HTML

后端 未结 4 1035
别跟我提以往
别跟我提以往 2020-11-29 06:29

Is there a way to control the load order of images on a web page? I was thinking of trying to simulate a preloader by first loading a light-weight \'LOADING\' graphic. Any

相关标签:
4条回答
  • 2020-11-29 07:06

    Here's a small jQuery plugin that does this for you: https://github.com/AlexandreKilian/imageorder

    0 讨论(0)
  • 2020-11-29 07:09

    I think this article https://varvy.com/pagespeed/defer-images.html gives a very good and simple solution. Notice the part which explains how to create "empty" <img> tags with:

    <img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="your-image-here">

    to avoid <img src="">

    To display a loading image, just put it in the HTML and change it later at the appropriate moment/event.

    0 讨论(0)
  • 2020-11-29 07:14

    Just include the 'loading' image before any other images. usually they are included at the very top of the page and then when the page loading completes, they are hidden by a JS.

    0 讨论(0)
  • 2020-11-29 07:15

    Use Javascript, and populate the image src properties later. The # tells the browser to link to a URL on the page, so no request will be sent to the server. (If the src property was empty, a request is still made to the server - not great.)

    Assemble an array of image addresses, and recurse through it, loading your images and calling a recursive function when the onload or onerror method for each image returns a value.

    HTML:

    <img src='#' id='img0' alt='[]' />
    <img src='#' id='img1' alt='[]' />
    <img src='#' id='img2' alt='[]' />
    

    JS:

    var imgAddresses = ['img1.png','img2.jpg','img3.gif'];
    
    function loadImage(counter) {
      // Break out if no more images
      if (counter==imgAddresses.length) { return; }
    
      // Grab an image obj
      var I = document.getElementById("img"+counter);
    
      // Monitor load or error events, moving on to next image in either case
      I.onload = I.onerror = function() { loadImage(counter+1); }
    
      //Change source (then wait for event)
      I.src = imgAddresses[counter];
    }
    
    loadImage(0);
    

    You could even play around with a document.getElementsByTagName("IMG").

    By the way, if you need a loading image, this is a good place to start.

    EDIT

    To avoid multiple requests to the server, you could use almost the same method, only don't insert image elements until you're ready to load them. Have a <span> container waiting for each image. Then, loop through, get the span object, and dynamically insert the image tag:

    var img = document.createElement("IMG");
    document.getElementById('mySpan').appendChild(img);
    img.src = ...
    

    Then the image request is made only once, when the element is created.

    0 讨论(0)
提交回复
热议问题