I use a script from internet named "jqueryscrollpagination" from online for auto loading content while user scrolling to the bottom because my page is too long.
Live link- http://www.arif-khan.net/project/chuck/jobOpening.html
My problem is it shows same content again & again after scrolling at the bottom. How can i fix it?
Javascript code-
<script type="text/javascript">
$(function(){
$('#content').scrollPagination({
'contentPage': 'more_content.html', // the url you are fetching the results
'contentData': {}, // these are the variables you can pass to the request, for example: children().size() to know which page you are
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends
'beforeLoad': function(){ // before load function, you can display a preloader div
$('#loading').fadeIn();
},
'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements
$('#loading').fadeOut();
var i = 0;
$(elementsLoaded).fadeInWithDelay();
if ($('#content').children().size() > 100){ // if more than 100 results already loaded, then stop pagination (only for testing)
$('#nomoreresults').fadeIn();
$('#content').stopScrollPagination();
}
}
});
// code for fade in element by element
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 100;
});
};
});
</script>
& it also uses another script file. Check here- http://www.arif-khan.net/project/chuck/scripts/scrollpagination.js
Just a guess, but if the url isn't changing each time, you will end up with a cached copy of the content causing the same data over and over unless the server is sending a no-cache header.
Related
What I want to do:
On page A, there are links to many pages e.g. page B, page C etc.
When I click on a link, I want the current page to fade out and the new page to fade in.
I searched a lot and got lots of jquery solutions - they work fine but I want to find out how I can do this in vanilla javascript only. I tried to work it out on my own but it doesn't work. I've already checked for console errors and put the JS script in the footer.
document.addEventListener("click", "a", function () {
// get the href attribute
var newUrl = this.attr("href");
// veryfy if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page)
document.querySelector("html").fadeOut(function () {
// when the animation is complete, set the new location
location = newUrl;
});
// prevent the default browser behavior.
return false;
});}
Done in vanilla javascript.
When you click on a link, the code snippet delays the default loading of the next page until the fade-out animation is complete.
document.querySelector("a").addEventListener("click", function () {
event.preventDefault();
// get the href attribute
var newUrl = this.getAttribute("href");
document.querySelector("body").addClass("fade-out");
// verify if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page). You need to set the duration manually.
//if you have an animation that lasts .5, 1 or 2 seconds etc, you need to put the duration below
var animationDuration = 500;
setTimeout(function() {
location = newUrl;}, animationDuration);
});}
You can use iframe inside modal popup and can open page in it.
See below links for reference :-
load iframe in bootstrap modal
I'm talking about an icon that is displayed on a tab during page loading.
Chrome:
Firefox (with TreeTab plugin):
You get the idea. I want to make it seem like the page is loading, when it's already loaded. Some event fires is javascript and then the tab looks like it's being loaded. Is there a way to do that?
One way I can think of is to replace a favicon with a spinner, but I'm not sure if it's possible to change on the fly and even if it is, it would be a hassle to make it cross-browser.
I don't think it is a good idea to do it, you'll make your users do a lot of useless requests, and this kills trees : /
IMO, it's better to do all you have in the page itself, and let the browser's UI do his own stuff.
But since I liked the challenge, here is one hacky way :
Loading an iframe will trigger this icon in both chrome and Firefox[1], so you could ,
append an iframe in the document,
set its src to some huge document,
onload of the iframe, set it again with a ? cache hack,
regularly check if the duration has elapsed so you can remove the iframe's src.
[1] It seems that Firefox does trigger the icon only if it was triggered when the document was still loading.
In code :
// how to use :
showTabLoader(25000);
// takes duration in ms as only parameter
function showTabLoader(duration) {
if (!duration) return;
var now = performance.now();
// To avoid flickering, you need some big document
// Please change this url in your script, wikimedia may not be happy with us.
var url = 'https://upload.wikimedia.org/wikipedia/commons/3/35/Viborg_Katedralskole_Symmetrical.jpg';
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.onload = function() {
if (performance.now() - now < +duration) {
this.src = url + '?' + Math.random();
}
};
var check = function(time) {
if (time - now > +duration) {
iframe.src = '';
iframe.parentNode.removeChild(iframe);
return;
}
requestAnimationFrame(check);
}
requestAnimationFrame(check);
iframe.src = url;
}
I recently thought of the same idea. A neat option is to use a dynamic favicon instead of hacking in hidden requests, which is a really bad idea in my opinion. I found this example. It's to much code to include here and doesn't work in iframes so no way of showing it directly on Stackoverflow. Instead i describe the idea behind.
https://www.cssscript.com/favicon-loading-indicator-favloader/
The idea is simple. Replace the favicon in an interval with the loading animation icons. A favicon cannot be GIF so you have to load each image step by step with JS. When you are done, simply replace it back with the original favicon.
For me this works at least in all chrome based browsers. Firefox throw some errors in this example, but i guess it can be fixed.
Alternitive:
There is no function that shows the actual loading process of the webpage. But you can do it manually, like you said!
The event below starts to run when the page is fully loaded, even after all the images are loaded:
$(window).on('load', function() {
// do stuff
});
So what you could do is set up your html like this:
<div class="preloader">
// your loader here, animations, video, gif, anything you want
</div>
<div class="main" style="display: none;">
// the page
</div>
and your jquery like this:
$(window).on('load', function() {
setTimeout(function() {
$('.preloader').css('display', 'none');
$('.main').css('opacity', '1');
}, 5000); // <-- 5seconds
});
And there you have your manual loading function! Works perfect.
Example website: ifly50
EDIT:
added code snippet
Code snippet:
$(window).on('load', function() {
setTimeout(function() {
$('.preloader').css('display', 'none');
$('.main').css('display', 'block');
}, 3000); // <-- 3 seconds
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preloader">loading</div>
<div class="main" style="display: none;">main</div>
I have a page with some fixed and absolute elements that are causing an issue for hash path links. I was able to fix it while the user is navigating around the page with function() { window.scrollBy(0, -80) }; however if I try to call this on my document ready (to scroll for incoming hashes) it does not work.
I found the reason it does not work is that the page does not actually adjust to the hash until after the document ready. If I cannot do this at document ready when can I do it?
As clearly the browser only scrolls to the HTML element from hash only after the whole page is loaded - including all JS -, I think the best option is to bind actions to the scroll event of the page.
You could try something like this:
<script type="text/javascript">
$(function() {
// Retrieves the hash from URL
var hash = window.location.hash.substring(1);
// If hash length > 0 (there is actually a hash)
// And the #hash element exists on page
if(hash.length > 0 && $('#'+ hash).size() > 0){
// Binds a function to the page scroll
$(document).on('scroll', function(){
// Here's the bright part: when the browser finish loading the page, it will
// scroll right to the #hash element. So, whenever the page is scrolled, if
// the #hash element offset top matches the page scroll offset, it means the page
// was scrolled right to that element.
var elemTop = $('#'+ hash).offset().top; // Retrieve element's offset top
var docTop = $(document).scrollTop(); // Retrieve page's offset
if(elemTop == docTop){
alert('Now I do my stuff!! :)');
// Do your stuff
}
// And now you make sure "your stuff" won't happen again if the user
// accidentally scrolls precisely to the #hash element's offset by
// unbinding scroll action of the page.
$(document).unbind('scroll');
});
}
});
</script>
I hope that help you to solve your problem! Let me know if anything was unclear.
I want to enable a lazy loading for the contents of my website.
Just like Jquery Image loading http://www.appelsiini.net/projects/lazyload that is valid only for images.
I want to do it for the content (DIV's).
Suppose we have a long page then i want to download the div as they becomes visible.
I will download the content using JSON or PageMethods. But i want the code that will execute the function for loading contents.
So whether we can somehow find this that div is visible only scrolling down.
Means i need to use some scroll events but dont know how.
Any help is appreciated.
I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
Also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window, it should be visible (or in this case: loaded). Your function lazyload() might look like this:
function lazyload(){
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
$(".ads").each(function(){
var ot = $(this).offset().top; //* top of object (i.e. advertising div)
var ob = ot + $(this).height(); //* bottom of object
if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
$(this).html("here goes the iframe definition");
$(this).attr("loaded",true);
}
});
}
I tested this on all major browsers and even on my iPhone. It works like a charm!!
The code below does not cover cases where the user scrolls up from the bottom (read patrick's comment below). Also, it allows multiple event executions because of several concurrent onscroll events (in most browsers you won't see this, most of the time).
$(document).ready(function(){
$(window).scroll(function() {
//check if your div is visible to user
// CODE ONLY CHECKS VISIBILITY FROM TOP OF THE PAGE
if ($(window).scrollTop() + $(window).height() >= $('#your_element').offset().top) {
if(!$('#your_element').attr('loaded')) {
//not in ajax.success due to multiple sroll events
$('#your_element').attr('loaded', true);
//ajax goes here
//in theory, this code still may be called several times
}
}
});
});
Proper solution, that takes into consideration scrolling from bottom here.
You may consider way point library :)
http://imakewebthings.com/waypoints/api/waypoint/
Its use cases and api's are defined in above link
It is of 9 kb when compressed. It will add an additional -100 ms- 50ms timelag while loading page on 3g/ 4g
Edit :-
It can be used standalone and it also supports all major frameworks.
Here is a solution that lazy loads images when they come within 500px of view. It can be adapted to load other types of content. The images themselves have an attribute data-lazy="http://..." with the image url in it, and then we just put a dummy transparent image for the src attribute.
var pixelLoadOffset = 500;
var debouncedScroll = debounce(function () {
var els = app.getSelector(el, 'img[data-lazy]');
if (!els.length) {
$(window).unbind('scroll', debouncedScroll);
return;
}
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
els.each(function () {
var $this = $(this);
var ot = $this.offset().top; //* top of object
var ob = ot + $this.height(); //* bottom of object
if (wt <= ob + pixelLoadOffset && wb >= ot - pixelLoadOffset) {
$this.attr('src', $this.attr('data-lazy')).removeAttr('data-lazy');
}
});
}, 100);
$(window).bind('scroll', debouncedScroll);
The debounce function I'm using is as follows:
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
}
You need to keep in mind that this isn't very effective on iOS, as the scroll event doesn't fire until after the user has finished scrolling, by which time they will already have seen the blank content.
We're using OpenX to serve ads on a number of sites. If the OpenX server has problems, however, it blocks page loads on these sites. I'd rather have the sites fail gracefully, i.e. load the pages without the ads and fill them in when they become available.
We're using OpenX's single page call, and we're giving divs explicit size in CSS so they can be laid out without their contents, but still loading the script blocks page load. Are there other best practices for speeding up pages with OpenX?
We load our ads in iframes to avoid the problem you're having. We size div and the iframe the same, with the iframe pointing to a page which just contains the ad snippet (you can pass the zone and other required options as parameters to that page).
cheers
Lee
We lazy-load OpenX's code. Instead of putting the single-page call at the top of the page, we put it at the bottom. After the page has loaded, the call will get the banner data and a custom code will add the correct banners in the correct zones.
The code below requires a proper DOM. If you have jQuery, DOMAssistant, FlowJS, etc, the DOM should be fixed for you.
This code will work with normal banners with images, flash, or HTML content. It may not work in some cases like when using banners from external providers (adform, etc). For that you may need to hack the code a bit.
How to use it?
add your SinglePageCall code towards the end of your HTML code
add this code under the SPC code.
after half a second or so, your OpenX code should be ready, and the code below will put the banners within the specified DIVs.
Oh, yeah, you need to add to your HTML code some DIVs as place holders for your banners. By default I have these banners set with CSS class "hidden" which totally hides the DIVs (with visibility, display, and height). Then, after the banner in a given DIV is successfully loaded, we remove the hidden class and the DIV (and the banner within) become visible.
Use at your own risk! :) Hope it helps
(function(){
if (!document || !document.getElementById || !document.addEventListener || !document.removeClass) {
return; // No proper DOM; give up.
}
var openx_timeout = 1, // limit the time we wait for openx
oZones = new Object(), // list of [div_id] => zoneID
displayBannerAds; // function.
// oZones.<divID> = <zoneID>
// eg: oZones.banner_below_job2 = 100;
// (generated on the server side with PHP)
oZones.banner_top = 23;
oZones.banner_bottom = 34;
displayBannerAds = function(){
if( typeof(OA_output)!='undefined' && OA_output.constructor == Array ){
// OpenX SinglePageCall ready!
if (OA_output.length>0) {
for (var zone_div_id in oZones){
zoneid = oZones[zone_div_id];
if(typeof(OA_output[zoneid])!='undefined' && OA_output[zoneid]!='') {
var flashCode,
oDIV = document.getElementById( zone_div_id );
if (oDIV) {
// if it's a flash banner..
if(OA_output[zoneid].indexOf("ox_swf.write")!=-1)
{
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[zoneid].substr(OA_output[zoneid].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ){
eval(flashCode);
oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[zoneid];
oDIV.removeClass('hidden');
}
}
}
} // end of loop
}//else: no banners on this page
}else{
// not ready, let's wait a bit
if (openx_timeout>80) {
return; // we waited too long; abort
};
setTimeout( displayBannerAds, 10*openx_timeout );
openx_timeout+=4;
}
};
displayBannerAds();
})();
OpenX has some documentation on how to make their tags load asynchronously:
http://docs.openx.com/ad_server/adtagguide_synchjs_implementing_async.html
I've tested it, and it works well in current Chrome/Firefox.
It takes some manual tweaking of their ad code. Their example of how the ad tags should end up:
<html>
<head></head>
<body>
Some content here.
Ad goes here.
<!-- Preserve space while the rest of the page loads. -->
<div id="placeholderId" style="width:728px;height:90px">
<!-- Fallback mechanism to use if unable to load the script tag. -->
<noscript>
<iframe id="4cb4e94bd5bb6" name="4cb4e94bd5bb6"
src="http://d.example.com/w/1.0/afr?auid=8&target=
_blank&cb=INSERT_RANDOM_NUMBER_HERE"
frameborder="0" scrolling="no" width="728"
height="90">
<a href="http://d.example.com/w/1.0/rc?cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
target="_blank">
<img src="http://d.example.com/w/1.0/ai?auid=8&cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
border="0" alt=""></a></iframe>
</noscript>
</div>
<!--Async ad request with multiple parameters.-->
<script type="text/javascript">
var OX_ads = OX_ads || [];
OX_ads.push({
"slot_id":"placeholderId",
"auid":"8",
"tid":"4",
"tg":"_blank",
"r":"http://redirect.clicks.to.here/landing.html",
"rd":"120",
"rm":"2",
"imp_beacon":"HTML for client-side impression beacon",
"fallback":"HTML for client-side fallback"
});
</script>
<!-- Fetch the Tag Library -->
<script type="text/javascript" src="http://d.example.com/w/1.0/jstag"></script>
Some other content here.
</body>
</html>
Following #Rafa excellent answer, i'm using this code to invoke OpenX banners after the page loads. I'm using jquery as well and had to add a new replace call for the "document.write" that flash banners use, and replacing it with "$('#"+ oDIV.id +"').append" instead. I'm using a custom "my_openx()" call, to replace "OA_show()". My banners area called by the zone_id and are wrapped inside a div, like this:
<div id="openx-4"><script>wm_openx(4);</script></div>
It's working :)
<script type="text/javascript">
$is_mobile = false;
$document_ready = 0;
$(document).ready(function() {
$document_ready = 1;
if( $('#MobileCheck').css('display') == 'inline' ) {
$is_mobile = true;
//alert('is_mobile: '+$is_mobile);
}
});
function wm_openx($id) {
if($is_mobile) return false;
if(!$document_ready) {
setTimeout(function(){ wm_openx($id); },1000);
return false;
}
if(typeof(OA_output[$id])!='undefined' && OA_output[$id]!='') {
var flashCode,
oDIV = document.getElementById('openx-'+$id);
if (oDIV) {
// if it's a flash banner..
if(OA_output[$id].indexOf("ox_swf.write")!=-1) {
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[$id].substr(OA_output[$id].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
flashCode = flashCode.replace(/document.write/, "$('#"+ oDIV.id +"').append");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ) {
//alert(flashCode);
eval(flashCode);
//oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[$id];
//oDIV.removeClass('hidden');
}
}
}
//OA_show($id);
}
</script>
I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window it should be visible (or in this case: loaded). Your function lazyload may look like this:
function lazyload(){
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
$(".ads").each(function(){
var ot = $(this).offset().top; //* top of object (i.e. advertising div)
var ob = ot + $(this).height(); //* bottom of object
if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
$(this).html("here goes the iframe definition");
$(this).attr("loaded",true);
}
});
}
Tested on all major browsers and even on my iPhone, works like a charm!!