-
Notifications
You must be signed in to change notification settings - Fork 93
/
infinite-jekyll.js
executable file
·85 lines (68 loc) · 2.45 KB
/
infinite-jekyll.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
$(function() {
var postURLs,
isFetchingPosts = false,
shouldFetchPosts = true,
postsToLoad = $(".post-list").children().length,
loadNewPostsThreshold = 3000;
// Load the JSON file containing all URLs
$.getJSON('/all-posts.json', function(data) {
postURLs = data["posts"];
console.log(postsToLoad);
// If there aren't any more posts available to load than already visible, disable fetching
if (postURLs.length <= postsToLoad)
disableFetching();
});
// If there's no spinner, it's not a page where posts should be fetched
if ($(".infinite-spinner").length < 1)
shouldFetchPosts = false;
// Are we close to the end of the page? If we are, load more posts
$(window).scroll(function(e){
if (!shouldFetchPosts || isFetchingPosts) return;
var windowHeight = $(window).height(),
windowScrollPosition = $(window).scrollTop(),
bottomScrollPosition = windowHeight + windowScrollPosition,
documentHeight = $(document).height();
// If we've scrolled past the loadNewPostsThreshold, fetch posts
if ((documentHeight - loadNewPostsThreshold) < bottomScrollPosition) {
fetchPosts();
}
});
// Fetch a chunk of posts
function fetchPosts() {
// Exit if postURLs haven't been loaded
if (!postURLs) return;
isFetchingPosts = true;
// Load as many posts as there were present on the page when it loaded
// After successfully loading a post, load the next one
var loadedPosts = 0,
postCount = $(".post-list").children().length,
callback = function() {
loadedPosts++;
var postIndex = postCount + loadedPosts;
if (postIndex > postURLs.length-1) {
disableFetching();
return;
}
if (loadedPosts < postsToLoad) {
fetchPostWithIndex(postIndex, callback);
} else {
isFetchingPosts = false;
}
};
fetchPostWithIndex(postCount + loadedPosts, callback);
}
function fetchPostWithIndex(index, callback) {
var postURL = postURLs[index];
$.get(postURL, function(data) {
$(data).find(".blog-post").appendTo(".post-list");
console.log(postURL);
console.log($(".post-list").children().length);
callback();
});
}
function disableFetching() {
shouldFetchPosts = false;
isFetchingPosts = false;
$(".infinite-spinner").fadeOut();
}
});