Edward
Edward

Reputation: 4918

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

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>

...

Upvotes: 1

Views: 56

Answers (2)

Mateus Felipe
Mateus Felipe

Reputation: 1161

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.

Upvotes: 1

Gaurav B
Gaurav B

Reputation: 356

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

this might help you in your situation.

Upvotes: 0

Related Questions