www.webdeveloper.com
Results 1 to 4 of 4

Thread: What is the best way to preload images located in other pages of my website?

  1. #1
    Join Date
    Mar 2012
    Posts
    18

    What is the best way to preload images located in other pages of my website?

    Hi
    A few pages on my website have different medium sized images.
    To speed up page loads, when users visit my home page, I would like to pre-load the other page's images
    into the browser cache.
    Should I add my preload script to the head section of my home page or should I place the script in an
    external javascript file and link the file to my home page?


    Code:
    function preloader()  {      
    // counter     var i = 0;      
    // create object    
    imageObj = new Image();     
     // set image list     
    images = new Array();    
    images[0]="image1.jpg"   
    images[1]="image2.jpg"    
    images[2]="image3.jpg"     
    images[3]="image4.jpg"      
    // start preloading     
    for(i=0; i<=3; i++)      {         
    imageObj.src=images[i];     
    }  }

  2. #2
    Join Date
    Mar 2011
    Posts
    1,141
    For the sake of speed, you should put the code in the <head> section of your home page and save the HTTP request required for loading an external script - especially since it's only 10 lines of code. For the sake of your users, attach preloader() to the home page's onload event so that the images don't start to load before your home page starts to render.
    Rick Trethewey
    Rainbo Design

  3. #3
    Join Date
    Mar 2012
    Posts
    18
    Thank you for replying.
    If I want to add say another 2 images to preloader do I change this i<=3; to this i<=5;

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,380
    Might be better to code the function this way ...
    Code:
    function preloader()  {      
      imageObj = new Image();     
     // set image list     
      images = ['image1.jpg','image2.jpg','image3.jpg','image4.jpg'];
    // start preloading     
      for (var i=0; i<=images.length; i++) { imageObj.src=images[i]; }
    }
    Advantage is that you would nust add the new image filenames to the "images" array.
    Then you need not worry about the "for" settings for the loop limit.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles