Click here to Skip to main content
Click here to Skip to main content

Tagged as

Secure and Lazy Image Loading in HTML 5

, 9 Jun 2014 Ms-PL
Rate this:
Please Sign up or sign in to vote.
Image loading using HTML5 web workers


Images are loaded on almost each and every website, the problem is that when they are loaded either they take too much time which causes a delay in web page performance and loading time or if they are loaded using a static (cookieless) domain then the performance effect the DNS. Even in this process a few images may be skipped during the loading. To avoid this with the availability of HTML5 we have passed the images onto the Web Workers which process them asynchronously and display them after loading the page. This does not effect the page performance and displays the images in a defined sequence. Further the images are rendered onto the page using opacity which varies from 0 to 1 and is looped through via another web worker. 


Create Two Web Workers:

  • First one will load the img tags (all those which have an id starting from alphanumeric character x)
  • Second one will set the image opacity one by one starting from 0 to 1.

Implementation and Code

To implement async image loading;

  • Move your images to folder images
  • Move spawn.js and spawnsub.js to folder scripts


Web workers are async so we won't have any blocking problems in the page loading. Feel free to use the attached code. Currently the number of images this will loop through is set to 10, where as the timeout is set to 1000 millisecond. Feel free to tweak it to meet your needs.

/*loading image tags starting with x*/

var i = 0;
function timedCount()
    if (i < 10) {
        setTimeout("timedCount()", 1000);


This part renders the image opacity from invisible to visible in multiples of 0.1, the current number of milliseconds which are set here are 200 but they can be changed as per need. What this worker does is add the parameter opacity and pass it to the image multiple times until the image attains the opacity level of 1 (i.e. it is fully visible).

/*rendering the image opacity*/

var i = 0;
function fading() {
    if (i < 10) {
        setTimeout("fading()", 200);
        var x = (i / 10).toString();
        var y = "opacity:".concat(x);

Both spawn.js and spawnsub.js return the data while looping through each other.


  1. Name the images with id="x1" to id="x10", you can select the sequence in which they will be loaded onto the page. The class tag should be used to set opacity, here I am using class="preload". Add this to the CSS of your page.
    .showopac{display:visible;opacity: 0}
    .preload{background-image: url('/images/sprite.gif'); width:10px; height:4px; background-repeat: no-repeat}

    Note that your source and alt tags will remain the same, like:

    <img id="x1" class="preload" src="/images/logo.png" alt="logo" />

    Add this script to the footer of your page.

                          /* copyrights 2014 moeen khurshid */
                          var w;
                          var e = document.getElementsByTagName("img").length;                     
                           function nWorker(r){
                              var en = new Worker('/scripts/spawnsub.js');                         
                              en.onmessage = function(eventx){       
                                      document.getElementById("x" + r).setAttribute
                                      if( == "opacity: 0.9")
                            function startWorker()
                                if (typeof (Worker) !== "undefined")
                                    if (typeof (w) == "undefined")
                                        w = new Worker("/scripts/spawn.js");
                                    w.onmessage = function(event) {
                                        if ( > 0 && <= e) {
                                            document.getElementById("x" + 
                                  "class", "showopac");
                                        else {
                                    /*this is a fail safe if workers are not there show images w jquery*/                               
                            function stopWorker()

Points of Interest

In future, a checksum can be used to calculate the hash of the image and compare it to the currently loaded image.



This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


About the Author


United States United States
No Biography provided

Comments and Discussions

QuestionThis was a tip... PinprotectorOriginalGriff7-Jun-14 20:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 9 Jun 2014
Article Copyright 2014 by moeenkhurshid
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid