1

Is there a way to load some images first, then (or meanwhile) others?

Here the HTML structure, I want all first images start to loading on the first time, order doesn't matter, when the image loaded doesn't matter (first image can be loaded after other images due to big size)

<ul>
  <li><img /></li> <!--first image-->
  <li><img /></li>
  <li><img /></li>
</ul>

<ul>
  <li><img /></li> <!--first image-->
  <li><img /></li>
  <li><img /></li>
</ul>

<ul>
  <li><img /></li> <!--first image-->
  <li><img /></li>
  <li><img /></li>
</ul>

<ul>
  <li><img /></li> <!--first image-->
  <li><img /></li>
  <li><img /></li>
</ul>

...
Edward
  • 4,858
  • 9
  • 37
  • 42
  • 1
    If you simply use raw HTML tags, you won't. But you can "inject" the images throught Javascript according to what have been loaded. – Mateus Felipe Apr 16 '17 at 16:17
  • Append images with JavaScript and add a timeout to the images you want to delay. – SrAxi Apr 16 '17 at 16:24

2 Answers2

1

You cannot with raw HTML. Although, you can add images through javascript depending on what have been loaded. Something like this:

<ul id="list">
  <li id="first-image"><img /></li> <!--first image-->
</ul>

Then, on javascript:

var list = document.getElementById('list');
var firstImage = document.getElementById('first-image');
var listItem = document.createElement('li');
var otherImage = document.createElement('img');

firstImage.onload = function () {
    listItem.appendChild(otherImage);
    list.appendChild(listItem);
};

I've not tested the code, but it's something like this. You can read more about it here and here.

Edit:

I was reading a little more about it, and I think there's a little issue with the code below. Using this way, the event is going to trigger when the DOM element has been loaded, and not neccesarily the image per se. I've found another solution:

var img = document.querySelector('img')

function loaded() {
  alert('loaded')
}

if (img.complete) {
  loaded()
} else {
  img.addEventListener('load', loaded)
  img.addEventListener('error', function() {
      alert('error')
  })
}

Source: this question.

Community
  • 1
  • 1
Mateus Felipe
  • 1,071
  • 2
  • 19
  • 43
0

There is a jQuery plugin that controls the order of image load: https://github.com/AlexandreKilian/imageorder

this might help you in your situation.

Gaurav B
  • 346
  • 2
  • 5