Home >Web Front-end >JS Tutorial >Simple implementation of javascript delayed loading technology (lazyload)_javascript skills

Simple implementation of javascript delayed loading technology (lazyload)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:11:52929browse

1. Foreword
Lazy loading technology (referred to as lazyload) is not a new technology. It is a solution for js programmers to optimize web page performance. The core of lazyload is on-demand loading. Lazyload can be found in large websites. For example, Google's image search page, Thunder homepage, Taobao, QQ space, etc. Therefore, mastering lazyload technology is a good choice. Unfortunately, the jquery plug-in lazy load official website (http://www.appelsiini.net/projects/lazyload) says it does not support it. New version of browser.

2. In what situations is lazyload more suitable?
It involves pictures, flash resources, iframes, web page editors (similar to FCK), etc., which take up a lot of bandwidth, and these modules are not available in browsers for the time being. Within the viewport, you can use lazyload to load this type of resource at the appropriate time. Avoid loading too many resources when the web page is opened and making users wait too long.

3. How to implement lazyload?
Difficulties of lazyload How to load the resources that the user needs at the appropriate time (the resources that the user needs here refer to the resources that are presented in the browser's visible area). Therefore, we need to know several pieces of information to determine whether the target has been presented in the client area, including:
 1. The position of the visual area relative to the top of the browser
2. The position of the resource to be loaded relative to the top of the browser.
After obtaining the above two points of data, you can use the following function to determine whether an object is in the browser's visible area.

Copy code The code is as follows:

// Return the browser’s visible area position
function getClient(){
var l,t,w,h;
l = document.documentElement.scrollLeft || document.body.scrollLeft;
t = document.documentElement.scrollTop || document.body.scrollTop;
w = document.documentElement.clientWidth; .documentElement.clientHeight;
Return {'left':l,'top':t,'width':w,'height':h} ;
}
//Return to the location of the resource to be loaded
function getSubClient(p){
var l = 0,t = 0,w,h;
w = p.offsetWidth;
h = p.offsetHeight;
while(p.offsetParent ){
 l = p.offsetLeft;
 t = p.offsetTop;
  p = p.offsetParent; 'width':w,'height':h } ;
}


 The function getClient() returns the browser client area area information, and getSubClient() returns the target module area information. At this time, determining whether the target module appears in the client area is actually determining whether the above two rectangles intersect.


Copy code The code is as follows: // Determine whether two rectangles intersect and return a Boolean value
function intens(rec1,rec2){
var lc1,lc2,tc1,tc2,w1,h1;
lc1 = rec1.left rec1.width / 2;
lc2 = rec2.left rec2.width / 2;
tc1 = rec1.top rec1.height / 2;
tc2 = rec2.top rec2 .height / 2;
  w1 = (rec1.width rec2.width) / 2;
  h1 = (rec1.height rec2.height) / 2;
return Math.abs(lc1 - lc2) < ; w1 && Math.abs(tc1 - tc2) < h1 ;
  }


Now we can basically implement delayed loading. Next, we write some in the window.onscroll event The code monitors whether the target area is rendered in the client area.


Copy the code The code is as follows:  < div style = "width:100px; height:3000px">
 
 

  var d1 = document.getElementById("d1");
Window.onscroll = function(){
  var prec1 = getClient();
var prec2 = getSubClient(d1);
if(intens(prec1,prec2)){
alert("true")
}

팝업 창에 필요한 리소스만 로드하면 됩니다.
여기서 주목해야 할 점은 대상 개체가 클라이언트 영역에 표시되면 팝업 창이 다음과 같이 계속해서 팝업된다는 점입니다. 따라서 먼저 팝업을 띄워야 합니다. 창 이후 이 영역의 모니터링을 취소하려면 여기서 배열을 사용하여 모니터링해야 할 개체를 수집합니다. 또한 onscroll 이벤트와 onresize 이벤트는 브라우저의 가시 영역 정보를 변경하므로 이러한 유형의 이벤트가 트리거된 후 대상 개체가 가시 영역에 있는지 다시 계산해야 합니다. () 함수는 이를 달성하기 위해 사용됩니다.(Thunder 홈페이지의 Lazyload 대상 객체가 브라우저의 가시 영역에 있는지 여부는 onresize 이벤트에서 다시 계산되지 않습니다. 따라서 먼저 브라우저 창을 특정 크기로 줄이면 , 이미지를 로드해야 하는 영역으로 스크롤한 다음 최대화를 클릭하면 이미지가 로드되지 않습니다. 하하, 나중에 필요합니다.

요소 추가:

코드 복사 코드는 다음과 같습니다.

// 브라우저 영역에 특정 하위 영역이 있는지 비교
function jiance(arr,prec1,callback){
var prec2;
for(var i = arr.length - 1 ; i >= 0 ;i--){
if(arr[i]) {
  prec2 = getSubClient(arr[i] );
if(intens(prec1,prec2)){
콜백(arr[i]);
모니터링 삭제
    delete arr[i] = getClient(); arr,prec1,function(obj){
    //리소스 로드...
   Alert(obj.innerHTML)
  })
 }
//하위 영역 1
  var d1 = document.getElementById("d1");
//하위 영역 2개
var d2 = document.getElementById("d2")
//눌러야 함 영역 컬렉션을 로드해야 함
var arr = [d1,d2];
window.onscroll = function(){
// 다시 계산
autocheck();
}
window.onresize = function(){
   / / Recalculate
  autocheck();

이제 팝업 창에 필요한 리소스만 로드하면 됩니다. 필요하신 분이나 질문이 있으신 분은 저에게 연락주세요.
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