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

Introduction

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. 

Logic

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

Spawn.js

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()
{
    i++;
    if (i < 10) {
        setTimeout("timedCount()", 1000);
        postMessage(i);      
    }
}
timedCount();

Spawnsub.js

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() {
    i++;
    if (i < 10) {
        setTimeout("fading()", 200);
        var x = (i / 10).toString();
        var y = "opacity:".concat(x);
        postMessage(y);
    }
}
fading();

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

Index.html

  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.

    <script>
                          /* 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
                                         ("style", event.data);
                                      if(event.data == "opacity: 0.9")
                                      {                                   
                                        en.terminate();
                                      }
                              }
                            }
                            function startWorker()
                            {
                                if (typeof (Worker) !== "undefined")
                                {
                                    if (typeof (w) == "undefined")
                                    {
                                        w = new Worker("/scripts/spawn.js");
                                    }
                                    w.onmessage = function(event) {
                                        if (event.data > 0 && event.data <= e) {
                                            document.getElementById("x" + 
                                            event.data).setAttribute("class", "showopac");
                                            nWorker(event.data);
                                        }
                                        else {
                                            stopWorker();
                                        }
                                    };
                                }
                                else
                                { 
                                    /*this is a fail safe if workers are not there show images w jquery*/                               
                                    $("img").addClass("show");
                                }
                            }
                            
                            function stopWorker()
                            {
                                w.terminate();
                            }
                            startWorker();
      </script>

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.

References

http://quadrantic.com/rel/moeenkhurshid?id=2&name=Secure-and-Lazy-Image-Loading-in-HTML5

License

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

Share

About the Author

moeenkhurshid

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