Home  >  Article  >  Web Front-end  >  jquery implements image preloading_jquery

jquery implements image preloading_jquery

WBOY
WBOYOriginal
2016-05-16 15:23:241136browse

Using jquery to implement image preloading improves page loading speed and user experience. This article will provide you with a detailed analysis of the implementation principle of jquery image preloading.

When to use image preloading?

If the page uses a lot of images that are not visible when loaded initially, it is necessary to preload:

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
 $('img').attr('src', arguments[i]);
 }
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');

We often encounter this problem when building websites: a page has a large number of pictures, which causes the page to load slowly, and a white page often appears, which makes the user experience very poor. So how to solve this problem? The first thing we will think of is to improve server performance and use static caching and other means to speed up the loading of images. This is indeed a good method, but sometimes we can also find some solutions from the front desk. Next, I will introduce a js preloading method that is often used in practical applications.
First, we do some processing when outputting the image836c0cefdc5398c9ffddff1174cd2181 After processing the html, we started to write js. Here I used the jquery class library. 

$('img[data]').load(function(){ 
 var __this__ = $(this); 
 var url = __this__.attr('data'); 
 var src = __this__.attr('src'); 
 if(url ==''|| url == src)//这里判断如果图片实际地址不存在或者已经加载不处理 
 { 
  return; 
 } 
 var img =newImage();//实例化一个图片的对象 
 img.src = url;//将要显示的图片加载进来 
  if(img.complete)//如果图片已经加载存在浏览器缓存中直接处理 
  { 
  __this__.attr('src',url);//将要显示的图片替换过来 
  return; 
  } 
  img.onload =function(){//要显示的图片加载完成后做处理 
  __this__.attr('src',url); 
  } 
}); 

Explanation with examples: Javascript, Jquery realizes page image preloading percentage display

If you need to show the loading progress when the page initially loads. Mainly refers to the case where there are many pictures:

You can use the third-party Jquery plug-in jquery.imgpreload.min.js
Just call the method inside: imgpreload. The example is as follows:

var imgNum = 0;
var images = [];
$(function(){ preloadImg(); });
 
//里面有两种方式
function preLoadImg() {
 //第一种方式:通过dom方法获取页面中的所有img,包括<img>标签和css中的background-image
 /*get all imgs those tag is <img>
 var imgs = document.images;
 for (var i = 0; i < imgs.length; i++) {
  images.push(imgs[i].src);
 }
 //get all images in style
 var cssImages = getallBgimages();
 for (var j = 0; j < cssImages.length; j++) {
  images.push(cssImages[j]);
 }*/
 
 //第二种方式:把所有该网页上用到的图片文件都预先放入一个数组里 
 $.imgpreload(['images/bg1.jpg', 'images/bg2.jpg'], function () {
   //此处是显示进度百分比时需要用到的背景图,这个可以先加载进去
 });
 
 //then push all other images in array to load 
 images.push("images/test_1.png");
 images.push("images/test_2.png");
 images.push("images/test_3.png");
 //。。。
 images.push("images/test_n.png"); 
 
 /*这里是真正的图片预加载 preload*/
 $.imgpreload(images,
 {
  each: function () {
   /*this will be called after each image loaded*/
   var status = $(this).data('loaded') &#63; 'success' : 'error';
   if (status == "success") {    
    var v = (parseFloat(++imgNum) / images.length).toFixed(2);
    $("#percentShow").html(Math.round(v * 100) + "<sup>%</sup>");    
   }
  },
  all: function () {
   /*this will be called after all images loaded*/
   $("#percentShow ").html("100<sup>%</sup>");
 
   $("percentShow").fadeOut(1000);   
   $(".main").show();
  }
 });
}
 
//get all images in style(此方法引用其他博客的)
function getallBgimages() {
 var url, B = [], A = document.getElementsByTagName('*');
 A = B.slice.call(A, 0, A.length);
 while (A.length) {
  url = document.deepCss(A.shift(), 'background-image');
  if (url) url = /url\(['"]&#63;([^")]+)/.exec(url) || [];
  url = url[1];
  if (url && B.indexOf(url) == -1) B[B.length] = url;
 }
 return B;
}
 
document.deepCss = function (who, css) {
 if (!who || !who.style) return '';
 var sty = css.replace(/\-([a-z])/g, function (a, b) {
  return b.toUpperCase();
 });
 if (who.currentStyle) {
  return who.style[sty] || who.currentStyle[sty] || '';
 }
 var dv = document.defaultView || window;
 return who.style[sty] ||
 dv.getComputedStyle(who, "").getPropertyValue(css) || '';
}
 
Array.prototype.indexOf = Array.prototype.indexOf ||
 function (what, index) {
  index = index || 0;
  var L = this.length;
  while (index < L) {
   if (this[index] === what) return index;
   ++index;
  }
  return -1;
 }

This will give the user a percentage prompt when there are many pictures on the page and the network speed is very slow.
Before doing this, since every local test loads very quickly, the percentage instantly reaches 100% and then disappears. To make it look like that, I also wrote a pseudo-percentage progress bar for reference only:

 var t = window.setTimeout("preLoad()", 100);
 function preLoad() {
  $("#loading div").animate({ width: step + "px" }, 50).text(step + "%");
  step += 1;
  if (step <= 100) {
   t = window.setTimeout("preLoad()", 100);
  } else {
   clearTimeout(t);
   $("#loading").fadeOut(1000);
   $("#preloadImg").fadeOut(1000);
   
   $(".main").show();
 }

After the page initialization is completed, there is a process of increasing the simulated percentage on the page. When it reaches 100%, the progress bar disappears and the main page is displayed. However, it has nothing to do with the actual page loading.

The above is a detailed study on jquery image preloading. I hope it will be helpful to everyone's study.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn