Delay image loading with jQuery

I have a page with several galleries including accordions and sliders. The problem is that the page takes forever to load. Is there a way of wrapping an image in a bit of code or applying a class to it to force it to load only after everything else is loaded?



Sure you can. Replace your img src attributes with a "#", and add a custom attribute, something like this:

<img src="#" data-delayedsrc="/img/myimage.png" />

Then, add a javascript line when your page loads that does something like this:

  $(this).attr('src', $(this).data('delayedsrc'));

If you're using jQuery (and I assume you are as this is tagged as such) take a look at the Lazy Load Plugin for jQuery. It delays the loading of images that are outside the viewport until the user scrolls to them.

Update 2015: This plugin was broken at one point, but now works again. The last comment says as much, but I almost missed it because it was hidden in the collapsed comments.


An easy way to delay loading images (and iFrames) is with a combination of pure JS, and the custom HTML5 data-* attribute. The src of the image initially can point to a loading GIF. The data-* attribute contains the URL path of the image you ultimately want to load. The pure JS sets up a delay (3000 milliseconds in the example below), and then executes the, which sets the image's src to the intended image.

The example below performs on each image with class="load-delay".

Live Example:


JS and jQuery:

$(document).ready(function () {
  setTimeout(function () {
    $('.load-delay').each(function () {
      var imagex = $(this);
      var imgOriginal ='original');
      $(imagex).attr('src', imgOriginal);
  }, 3000);

HTML and jQuery Library:

<!DOCTYPE html>
<html lang="en" xmlns="">
<script src=""></script>
    <meta charset="utf-8" />

  <h1>Loading-Delayed Image</h1>
  <img class="load-delay" src="" data-original="" />

Keep only one image into the HTML so that viewer has something to start with, then inject the rest using jQuery with

$(document).ready(function() {
    //load rest of the images

You can also use event loaders and AJAX or "load as you go", just build a simple call back function if it's auto-rotating gallery or load on click.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.