JS mass image preloading


/ Published in: JavaScript
Save to your folder(s)

wrote this snippet as a necessity to preload many images without writing same code all the time in JS...


Copy this code and paste it in your HTML
  1. function displayElem(elem) {
  2. if(document.getElementById(elem) != null) {
  3. document.getElementById(elem).style.display = 'block';
  4. } else {
  5. window.setTimeout(function() {
  6. displayElem(elem);
  7. }, 80);
  8. }
  9. }
  10.  
  11. function preloadSuzukies(suz_obj) {
  12. var smatch = suz_obj.constructor.toString().match(/([^\(\)\s]+)\(\)/);
  13. switch(smatch[1]) {
  14. case "String":
  15. objImg = new Image();
  16. objImg.src = suz_obj;
  17. break;
  18. case "Object":
  19. var objArray = [];
  20. for(var i in suz_obj) {
  21. objArray.push(new Image());
  22. objArray[objArray.length - 1].src = suz_obj[i][0];
  23. if(typeof suzuki_imgs[i][1] !== "undefined") {
  24. objArray[objArray.length - 1].onload = (function(iter) {
  25. displayElem(suz_obj[iter][1]);
  26. })(i);
  27. }
  28. }
  29. break;
  30. case "Array":
  31. for(var i = 0; i < suz_obj.length; i++) {
  32. objImg = new Image();
  33. objImg.src = suz_obj[i];
  34. }
  35. break;
  36. default:
  37. alert("wrong argument is given for image preloading");
  38. break;
  39. }
  40. }
  41. var suzuki_imgs = {
  42. img1: ['images/suzuki_car.png', 'car_bg'],
  43. img2: ['images/get_spec_hover.png']
  44. };
  45. preloadSuzukies(suzuki_imgs);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.