When browsing the Web page on the mobile phone, often use a function, when we browse Jingdong or Taobao, the page slide to the bottom, we see the data automatically loaded into the list. I didn't know how these functions were implemented, so I simulated the functionality on my PC browser. First look at the browsing effect:
When the scroll bar scrolls to the bottom of the page, you are prompted to "load ...".
When the page has loaded all the data, scrolling to the bottom of the page prompts the "data is loaded to the end":
The process of implementing an infinite load of data is roughly as follows:
1. The scroll bar scrolls to the bottom of the page.
2. Triggers Ajax loading to load the requested data back into the list.
How do I tell if the scroll bar scrolls to the bottom of the page? We can set a rule: when the scroll height of the scrollbar is less than 20 pixels from the entire document height, the scroll bar is considered to scroll to the bottom of the page:
Document height-viewport height-scroll bar scrolling Height < 20
To achieve such a judgment through code, we have to understand which of the above heights is obtained through which code? You can refer to an article I wrote earlier, "HTML element coordinates positioning, these knowledge points to grasp."
The above judgment, I encapsulate a method:
Detects whether the scroll bar scrolls to the bottom of the page
function Isscrolltopagebottom () {
//document height
var documentheight = Document.documentElement.offsetHeight;
var viewportheight = Getviewportsize (). h;
var scrollheight = Window.pageyoffset | |
Document.documentElement.scrollTop | |
Document.body.scrollTop | | 0;
Return Documentheight-viewportheight-scrollheight <
}
With that in hand, we can turn on a timer, 900 milliseconds to monitor once, and if Isscrolltopagebottom () returns True, invoke Ajax request data, and if returned false, it will be monitored after 900 milliseconds.
Here is the core code implementation:
In the demo Ajax request I am through the Jquery-mockjax simulation data. The code is as follows:
/**
* Analog interface.
* *
var i = 0, Len =, addresses = ["Sichuan", "Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Gansu", "Yunnan", "Zhejiang", "Qinghai", "Guizhou"];
function GetData () {
var size = math.min (i +, len), arr = [];
for (; i < size; i++) {
Arr.push ({
name: "Apple" + (i% + 1),
Pic: "Assets/images/iphone" + (i% 10 + 1) + ". JPG ",
price:parseint (math.random () * 10000),
Star:parseint (Math.random () * 1000),
address:addresses [I%]
}
}
return arr;
}
$.mockjax ({
URL: ' http://localhost:8800/loaddata* ',
responsetime:1000,
response:function ( Settings) {
This.responsetext = {
status:true,
data:getdata ()}}}
);
The entire demo I have uploaded to the github:
Https://github.com/heavis/pageLoader
Online Demo:
Https://heavis.github.io/pageLoader/index.html
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.