ajax infinate scroll to preload content - javascript

I have an infinate scrolling function that loads data via ajax. I would like to load the next set of data or at least, images in advance - preload the next page of content.
I have tried adding .load instead of .ajax - but it still seems to load the data directly not from a 'cached' version.
Any ideas appreciated.
jQuery(document).ready(function($) {
var count = 2;
var total = <?php echo $wp_query->max_num_pages; ?>;
var ready = true; //Assign the flag here
var processing;
$(window).data('ajaxready', true).scroll(function() {
if ($(window).data('ajaxready') == false) return;
if ($(window).scrollTop() == ($(document).height() - $(window).height())){
$(window).data('ajaxready', false);
if (count > total){
return false;
}else{
loadArticle(count);
}
count++;
}
});
function loadArticle(pageNumber){
$('a#inifiniteLoader').show('fast');
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop',
success: function(html){
$('a#inifiniteLoader').hide('1000');
$(".newsfeed").append(html); // This will be the div where our content will be loaded
console.log('fire');
//stop multiple firing
$(window).data('ajaxready', true);
}
});
return false;
}
});

First I should say what is infinite scroll:
Traditionally, the user would have to click on next page or previous page to visit older post content. However, recently there is
a new trend started by popular sites (such as facebook and twitter) in
which they automatically load the next page content once the user hits
the bottom of the post. This technique has proven to show an increase
in time spent on page by the user because the new content loads
automatically.
How to Add Infinite Scroll in WordPress
First thing you need to do is install and activate the Infinite Scroll plugin.
Upon activation, a new menu option will be added under your settings
tab called Infinite Scroll. On almost 90% of the blog sites, this
should work without changing a single setting. However, if you have a
relatively custom designed blog, then you will need to adjust the
“Selectors”. Go the plugin’s setting page and click on the selectors
tab.
plugin
Documentation 1
documentation 2

Related

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>

Ajax GET is getting called twice (in Endless Scroll)

I have an endless scrolling made by ajax and jQuery. It's using the items paginated in Controller (Laravel5), getting it with ajax.
Everything works fine, however I have a problem. When I hit the bottom of the page, it makes an ajax call twice. I suspect it's because of the setInterval because when I change the time, it affects exactly that part.
// Creates the pagination pages [<[1]2]3]>]
{!! $boxes->render() !!}
// Html
<input type="hidden" id="page" value="1" />
<input type="hidden" id="max_page" value="{{{ $boxes-id }}}" />
<div id="end_of_page" class="center">
<hr/>
<span>End of the feed.</span>
<script>
$(document).ready(function() {
var didScroll = false;
$(window).scroll(function() { //watches scroll of the window
didScroll = true;
});
//Sets an interval so your window.scroll event doesn't fire constantly. This waits for the user to stop scrolling for not even a second and then fires the pageCountUpdate function (and then the getPost function)
setInterval(function() {
if (didScroll){
didScroll = false;
if(($(document).height()-$(window).height())-$(window).scrollTop() < 10){
pageCountUpdate();
}
}
}, 250);
When I change 250 to 5000 for example, it gives a time in between, but this is not what I want to make. I want to make the call only one time once I hit the bottom, maybe disable it with a boolean variable, and then reactivate it after new elements load (on ajax success state), but I couldn't figure it out where to put the blocking variable.
//Continuing
function pageCountUpdate(){
var page = parseInt($('#page').val());
var max_page = parseInt($('#max_page').val());
if(page < max_page){
$('#page').val(page+1);
getPosts();
$('#end_of_page').hide();
} else {
$('#end_of_page').fadeIn();
}
}
function getPosts(){
var data = { "page": $('#page').val() }
$.ajax({
type: "POST",
//Classic ajax call
beforeSend: function(){
..}
complete: function(){
..}
success: function(){
..}
});
}
}
});
Update: Regarding to John Resig's example mentioned in comments, I need to use var outerPane = $details.find(".details-pane-outer"),
didScroll = false;. I think not having this part creates my problem, but I couldn't figure out where to choose with find() method.
apart from your weird setinterval structure (just move the code into the scroll event, without an interval).
It seems that the scroll event is called multiple times inside the last 10 pixels of the bottom of the page. So while scrolling to the bottom, at 9 px away form the bottom, the event is fired which loads more posts. But even before the new posts are loaded, in the meanwhile you scroll a little further which again fires the scroll event. This makes your posts load twice or even more than twice.
To solve this you can add a simple boolean switch that makes sure that the posts don't get loaded again when they're already being loaded. Something like:
var loading=false;
function onReachScrollLimit(){
if(loading){return;}
loading=true;
load_new_posts();
}
function load_new_posts(){
//insert the posts
loading=false;
}

How to refresh a Div every 10 seconds without refreshing the entire page?

I'm working on a website platform that doesn't allow for any server sided scripting, so jquery and javascript are pretty much all I have to work with. I am trying to create a script to work with the site that will update a div that contains an inbox message count every 10 seconds. I've been successful with making the div refresh every ten seconds, but the trouble lies in the page views count. My script is refreshing the whole page and counting for a page view, but I only want to refresh just the one div. An example of the trouble my script causes is when viewing anything on the site that has a page view counter (forum posts, blog posts, ect...), the page views go crazy because of the script refreshing. I'm pretty new to Javascript, so I'm not entirely sure there is a way around this.
What I'm working with is below:
<div id="msgalert" style="display: none"; "width: 100px !important">
You have $inbox_msg_count new messages.
</div>
$inbox_msg_count is a call that grabs the message count, and provided by the platform the site is on. It displays the message count automatically when used.
Then the script that does all the work is this:
<script>
setInterval(function(facepop){
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
}, 1000);
facepop();
</script>
<script>
setInterval(function() {
$("#msgalert").load(location.href+" #msgalert>*","");
}, 1000); // seconds to wait, miliseconds
</script>
I realize I've probably not done the best job of explaining this, but that's because I'm pretty confused in it myself. Like I mentioned previously, this code function just how I want it, but I don't want it to refresh the entire page and rack up the page views. Any help is much appreciated.
You might try to look into iframe and use that as a way to update/refresh your content (div). First setup an iframe, and give it an id, then with JS grab the object and call refresh on it.
well your prob seems a little diff so i think submitting a from within the div might help you so ...
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../member/uploadTempImage',//serverURL
type:'post',
beforeSend:function()
{
alert(" if any operation needed before the ajax call like setting the value or retrieving data from the div ");
},
success:function(e){
alert("this is the response data simply set it inside the div ");
}
});
});
I think this could probably be done without a form, and definitely without iframes (shudder)..
Maybe something like this?
$(document).ready(function()
{
setInterval(function(facepop)
{
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
$.ajax({
type: "POST",
url: location.href,
success: function(msg)
{
$("#msgalert").html(msg);
}
});
},1000);
It's not entirely clear exactly what you're trying to do (or it may just be that I'm ultra tired (it is midnight...)), but the $.ajax() call in the above is the main thing I would suggest.
Encapsulating both functions in a single setInterval() makes things easier to read, and will extinguish the 1 second gap between showing the msgalert element, and "re-loading" it.

How to set the duration of a "loading spinner", based on the loaded content

I've made a loading "animation.gif" for my dynamic website. This is the code I used from jquery, to show and hide the spinner:
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
http://docs.jquery.com/Ajax_Events
My Problem:
The website has different contents (like flash, images, text etc.). So some parts of the website take longer to load then others. But the duration of loading animation is always the same(its too fast). When I load a content with a flash(4mb) and html text, the spinner hides way too fast, and the content is still loading. The same with HQ images..
I could use a min delay, like:
$("#this").delay(600).fadeOut("slow");
But I dont think this is a good solution at all.
How is it possible not to hide the loading-spinner, until the whole content is loaded?
What you can is create a list of flags for all of the slow loading elements in your page.
Then start listening to each of the elements load event ( You can do it with flash as well ).
Each time an element is loaded raise its flag.
Have a interval run in the background that watch this list, once all of list items are raised, remove the loading-spinner.
You can also try this:
var iv = setInterval(function () {
if (document.all["theObject"].readyState == 4) {
clearInterval(iv)
alert("Object loaded (maybe).")
}
}, 100)
taken from : http://www.webdeveloper.com/forum/showthread.php?160792-lt-object-onload,
by Orc Scorcher
From the very page you linked to, just bind to ajaxStart and ajaxStop instead, which have the required logic built-in and only fire for the first AJAX request in any group, and when the last AJAX request completes.
Alternatively, you can use your own counter to figure out how many AJAX requests are outstanding:
(function(sel) {
var count = 0;
$(sel).bind("ajaxSend", function() {
if (count++ === 0) {
$(this).show();
}
}).bind("ajaxComplete", function() {
if (--count === 0) {
$(this).hide();
}
});
})('#loading');
Ok I tried out this one (Fiddle Here) and hope is what you're looking for.
Basically:
give each element you want the loader to wait for a .content class
dynamically set content src with your jQuery/AJAX whatever
bind $('.content') elements to a .load() event
when .load() is fired increment a counter, if the counter equals the .length of $('.content') selector then hide the loading gif
From jQuery Site about .load() event :
This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
So it should work fine with your lazy content.
Hope it helps!

loading bar on loading new content

I have a div which contains a series of design projects. When the user scrolls to the bottom of the page, the javascript detects this and loads new page content into that div.
You can see the website at
http://www.jb-design.me/marchupdate/
The problem I have is that the new content just pauses then loads below. With no feedback for the user that new content is being loaded etc.
What I would like is a div to appear between the current content and the new content (Where the 'spacer' div normally is on my website. And display a loading gif/png. Which would fade out once the new content has loaded. The new content would then appear below fading in...?
Is this possible at all?
I have tried to implement a 'var pageLoadisloaded' but to no use.
I am literally a newbie and have been trailing the web for a solution for the past couple of days and now I thought I would just ask for help!
Thank you in advance
Javascript code below...
alreadyloading = false;
nextpage = 2;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (alreadyloading == false) {
var url = "page"+nextpage+".html";
alreadyloading = true;
$.post(url, function(data) {
$('#newcontent').children().last().after(data);
alreadyloading = false;
nextpage++;
});
}
}
});
After you set the alreadyloading variable to true, append a bit of html to the end of the div#newcontent which contains an image that indicates that new content is being loading. Use $(window).ScrollTop() to scroll further down to ensure that this is visible. When the content arrives via Ajax, you can remove the little piece of code you added, and append the new stuff.
Alternatively, use 3 div tags as follows:
1) The already loaded content is kept in the first division.
2) When the scroll-bar reaches the bottom, your function is triggered, which calls a jQuery FadeIn effect for the second division which contains the loading image. Scroll down a bit using the aforementioned function to ensure that it is visible.
3) When the content arrives, put it in the third div and then call a simultaneous FadeIn effect for that, and FadeOut effect for the second division.
4) Once the effect is complete, append the contents of the third division to the first one, and reset the third one.
What if you were to have a fixed div to the bottom of the page, and when you were in the conditional to load a new page - you fade it in, and when the new content has been loaded in - you fade it out?
Additional assistance
You could try something like this to check if more pages are available - set this up to run after the first ajax - perhaps in the success part of the function:
var url = "page"+nextpage+".html";
$.ajax({
url: url,
type:'HEAD',
error:
function(){
// No more pages exist - remove loading
$('#loading').remove();
},
success:
function(){
// Good to load another page
}
});
Where I found this:
http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

Categories

Resources