<pedrocorreia.net ⁄>
corner
<mySearch ⁄> <mySearch ⁄>

corner
 
corner
<mySnippets order="rand" ⁄> <mySnippets order="rand" ⁄>

corner
 
corner
<myContacts ⁄> <myContacts ⁄>

<email ⁄>


pc@pedrocorreia.net

<windows live messenger ⁄>


pedrojacorreia@hotmail.com

<myCurriculum type="pdf" ⁄>


Download
corner
 
corner
<myBlog show="last" ⁄> <myBlog show="last" ⁄>

corner
 
corner
<myNews show="rand" ⁄> <myNews show="rand" ⁄>

corner
 
corner
<myNews type="cat" ⁄> <myNews type="cat" ⁄>

corner
 
corner
<myQuote order="random" ⁄> <myQuote order="random" ⁄>

corner
 
corner
<myPhoto order="random" ⁄> <myPhoto order="random" ⁄>

<pedrocorreia.net ⁄>
corner
 
corner
<myAdSense ⁄> <myAdSense ⁄>

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<Javascript Image Preload ⁄ >




clicks: 17032 17032 2008-07-13 2008-07-13 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This



There are various ways to preload images in a html page and there are many reasons for you to want to preload some web content, like images for example when you're building a gallery or some effects, the delay in image loading may ruin your effect.

You'll have to use very carefully image preloading, if for instance, you're preloading many or heavy images you'll delay the page presentation and maybe your user will get tired of waiting and simply go away.
A simple trick is to place the loading immediately before the closing tab body, with this you webpage will be loaded, the user will see something, which will makes him be more patiently and the images will be preloaded at the end. I won't exemplify this trick, I'll preload the image during body onload, although this might not be the most advisable way, it's up to you to decide, since every webpage's a webpage.

We can use some techniques like: JavaScript; Css; JavaScript & Css. I'll use JavaScript and Css.

Initially I was just using JavaScript, however when doing some tests, I realized that IE wasn't caching images, the trick to bypass this was to create a dummy preloader div and append all the images to there.
Well since you just want to preload the images, and definitely don't want to show them to your user, you can style that div for not showing or give it an absolute position with negative positioning, etc, etc. In this example I'll just hide the div using "display: none;".
After doing this IE was starting to preload images, hooray!


Events.js - this file's responsible for events management, that is, our page has elements and those elements will react to events/ triggers, with this class we'll be able to add or remove events, such as onchange, onload, etc, etc.
  1. /**
  2. * Static Class Events
  3. * Manage Events
  4. */
  5. Events = function(){}
  6.  
  7. /**
  8. * Add Event
  9. *
  10. * Full credits to (I just made a few mods):
  11. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  12. *
  13. * @param Object
  14. * @param Object
  15. * @param Object
  16. */
  17. Events.AddEvent = function(obj, type, fn){
  18. if(!obj) return;
  19.  
  20. this.RemoveEvent(obj, type, fn);
  21. if (obj.addEventListener) {
  22. obj.addEventListener(type, fn, false);
  23. }
  24. else {
  25. if (obj.attachEvent) {
  26. obj["e" + type + fn] = fn;
  27. obj[type + fn] = function(){
  28. obj["e" + type + fn](window.event);
  29. }
  30. obj.attachEvent("on" + type, obj[type + fn]);
  31. }
  32. }
  33. }
  34.  
  35. /**
  36. * Remove Event
  37. *
  38. * Full credits to (I just made a few mods):
  39. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  40. *
  41. * @param Object
  42. * @param Object
  43. * @param Object
  44. */
  45. Events.RemoveEvent = function(obj, type, fn){
  46. if (obj.removeEventListener) {
  47. try{obj.removeEventListener(type, fn, false);} catch(e){}
  48. }
  49. else{
  50. if (obj.detachEvent) {
  51. obj.detachEvent("on" + type, fn);
  52. obj[type + fn] = null;
  53. obj["e" + type + fn] = null;
  54. }
  55. }
  56. }




ImagePreloader.js - this Class will be responsible to preload the images. We can preload as many images as we want (but please just bear in mind that it's not advisable to preload lots or heavy images, or you'll be at risk of your user close your webpage tab).

This class can receive as many arguments as you want to, regarding that the first argument's the preloader div name, the following arguments must have a Json format with a specific structure, but we'll see this ahead ...

  1. /**
  2. * This Class's responsible to preload the images
  3. *
  4. * @param String Div where images will be preloaded
  5. * @param Object
  6. * @param [Optional] Object(1) ... Object(n)
  7. *
  8. * @author pedrocorreia.net
  9. */
  10. ImagePreloader = function(div, obj /**,objs */){
  11. this.args = arguments; //assign attribute
  12.  
  13. /**
  14. * Preload Images
  15. */
  16. this.Preload = function(){
  17. //check if we have a valid placeholder
  18. if(!$(this.args[0])) throw("DIV_NOT_FOUND");
  19.  
  20. //check placeholder style display
  21. if($(this.args[0]).style.display!="none"){
  22. //if it's visible, then let's hide it...
  23. $(this.args[0]).style.display="none";
  24. }
  25.  
  26. var count_args = this.args.length, count = 0;
  27.  
  28. //iterate object arguments, starting at 2nd element,
  29. //because the 1st element args[0] stores
  30. //our dummy div preloader
  31. for (var i = 1; i < count_args; i++){
  32. var img_pre = this.args[i];
  33.  
  34. if (_is_array(img_pre.images)) {
  35. count = img_pre.images.length;
  36.  
  37. //iterate images array and load them
  38. for (var j = 0; j < count; j++) {
  39. _load(img_pre.folder, img_pre.images[j], this.args[0]);
  40. }
  41. }
  42. else {
  43. _load(img_pre.folder, img_pre.images, this.args[0]);
  44. }
  45. }//end iterate object arguments
  46.  
  47. }//end method Preload
  48.  
  49. /**
  50. * Private Method
  51. *
  52. * Create a new DOM Image and load it
  53. *
  54. * @param String Folder Name
  55. * @param String Image Name
  56. * @param String Div where images will be preloaded
  57. */
  58. var _load = function(folder, img, div){
  59. if(!img || !div) return;
  60.  
  61. var _dummy_img=new Image();
  62. _dummy_img.src=_folder(folder) + escape(img);
  63.  
  64. $(div).appendChild(_dummy_img);
  65. } //end private method _load
  66.  
  67. /**
  68. * Private Method
  69. *
  70. * Finds if the given argument is an array
  71. *
  72. * @param Object
  73. * @return Bool
  74. */
  75. var _is_array = function(obj){return (obj instanceof Array);}
  76.  
  77. /**
  78. * Private Method
  79. *
  80. * Check if we have a valid folder, this is,
  81. * with a slash "/" at the end
  82. *
  83. * @param String Folder
  84. * @return String
  85. */
  86. var _folder = function(folder){
  87. if (_right(folder, 1) != "/") {folder = folder + "/";}
  88. return folder;
  89. } //end method _folder
  90.  
  91. /**
  92. * Private Method
  93. *
  94. * Extract the rightmost part of a String
  95. *
  96. * @param String String to extract chars
  97. * @param Int Number of chars
  98. */
  99. var _right = function right(str, n){
  100. if(str=="" || n<=0) return "";
  101.  
  102. var len = String(str).length;
  103. return (n>len)?str:String(str).substring(len,len-n);
  104. } //end method _right
  105. }
  106.  
  107. /**
  108. * Get element reference
  109. *
  110. * @param Object
  111. * @return Object Reference
  112. */
  113. $ = function(elem){
  114. if(document.getElementById) return document.getElementById(elem);
  115. }






As I already said, the arguments must be in a valid Json format with a specific structure. We can just preload one image, but we may need to preload 2+ images, well we can create 2 variables, or we can use an array. See this example:


var img = {
"folder": "http:⁄⁄www.pedrocorreia.net⁄",
"images": "image1.jpg"
};



We're creating a variable with 2 fields: folder and images.
As you can easily see our image will have the following url:
- http: ⁄⁄www.pedrocorreia.net⁄image1.jpg
But what if we to preload 5, 6, ... n images? We could just create those n variables ... well that's unnecessary, we could just turn our field images to an array, to achieve this we can use square brackets "[]", like the following example:


var imgs = {
"folder": "http:⁄⁄www.pedrocorreia.net⁄",
"images": ["image1.jpg", "image2.jpg"]
};


By doing this we're just telling "hey, just preload, for me, these images "image1.jpg" and "image2.jpg", the script will be smart enough to detect if we're giving it multiple images or just one.








Init.js - this is where initially events will be triggered. We'll create the object and specify the images we want to preload.
  1. /**
  2. * Startup function
  3. *
  4. * @author pedrocorreia.net
  5. */
  6. Init = function(){
  7. //create json object with just one image
  8. var img = {
  9. "folder": "http://www.pedrocorreia.net/",
  10. "images": "dp_small.jpg"
  11. };
  12.  
  13. //create json object with multiple images
  14. var imgs1 = {
  15. "folder": "_images_/",
  16. "images": [
  17. "image3.jpg",
  18. "image4.jpg",
  19. "image5.jpg"
  20. ]
  21. }
  22.  
  23. //create another json object with multiple
  24. //images that are in "img" subfolder
  25. var imgs2 = {
  26. "folder": img.folder+"subfolder/",
  27. "images": [
  28. "image6.jpg",
  29. "image7.jpg",
  30. "image8.jpg"
  31. ]
  32. }
  33.  
  34. //create object
  35. var preloader = new ImagePreloader("dummy_preloader",img,imgs1,imgs2,{"folder": "../my_previous_folder/", "images": "image.png"});
  36.  
  37. //invoke preloading
  38. try{
  39. preloader.Preload();
  40. }
  41. catch(err){
  42. alert(err);
  43. }
  44. }
  45.  
  46. Events.AddEvent(window,"load",Init);




example html file - just a normal file, will have reference to our JavaScript file, Css, and we'll define our preloader div:

<div id="dummy_preloader" class="hidden"></div>


(I'll declare Css inside <head> tag, albeit it's advisable to use a separate stylesheet)

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head>
  5. <title>Javascript Image Preloader</title>
  6. <script type="text/javascript" src="Events.js"></script>
  7. <script type="text/javascript" src="ImagePreloader.js"></script>
  8. <script type="text/javascript" src="Init.js"></script>
  9.  
  10. <style type="text/css">
  11. .hidden{display: none;}
  12. </style>
  13.  
  14. </head>
  15. <body>
  16. Content goes here, regarding that all images were preloaded ...
  17. <div id="dummy_preloader" class="hidden"></div>
  18. </body>
  19. </html>






With this example the images preloaded will be:


http:⁄⁄www.pedrocorreia.net⁄dp_small.jpg
_images_⁄image3.jpg
_images_⁄image4.jpg
_images_⁄image5.jpg
http:⁄⁄www.pedrocorreia.net⁄subfolder⁄image6.jpg
http:⁄⁄www.pedrocorreia.net⁄subfolder⁄image7.jpg
http:⁄⁄www.pedrocorreia.net⁄subfolder⁄image8.jpg
..⁄my_previous_folder⁄image.png





If you have any doubt or found any error, please drop me an email









clicks: 17032 17032 2008-07-13 2008-07-13 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This