Implementing Infinite Scrolling with jquery - javascript

I am working on a project that uses the jQuery Masonry and Infinite Scroll plugins to load "n" amount of pictures from instagram using their API. Looking at this short example my understanding is that I need to have before hand the html pages to be rendered:
<nav id="page-nav">
  
</nav>
The problem is, I dont really know how many pictures will be retrieved. Here is for example how I retrieve 20 pics at a time.
$(document).ready(function(){
var access_token = location.hash.split('=')[1];
if (location.hash) {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/MY_USER_ID/media/recent/?access_token=MY_ACCESS_TOKEN",
success: function(data) {
for (var i = 0; i < 20; i++) {
$("#instafeed").append("<div class='instaframe'><a target='_blank' href='" + data.data[i].link +"'><img src='" + data.data[i].images.standard_resolution.url +"' /></a></div>");
}
}
});
} else {
location.href="https://instagram.com/oauth/authorize/?display=touch&client_id=MY_CLIENT_ID&redirect_uri=MY_URI";
}
});
I guess I will need a pagination mechanism but based on the tutorial mentioned above I believe I will first need to pre-define the html pages to be loaded. So now here my questions
Does that mean this plugin (Infinite Scroll) requires to have "n" amount of html files in a directory to achieve infinite scrolling?
Is it possible to implement infinite scrolling with the same plugin if I dont know how many pages I will have. Even better without even having to create physical html files?
How can this kind of pagination is implemented? (i.e loading chunks of 20 pics as long as the user keeps scrolling down) there is not that much documentation online, could you provide a short step through demo or description?
With kind regards

1) Does that mean this plugin (Infinite Scroll) requires to have "n" amount of html files
Absolutely not. You do not need to generate static html pages beforehand, The only think you need is a URL scheme where subsequent page content can be fetched by changing one number in URL.
Think of it from the perspective of the infinite scroll plugin. You load the plugin JavaScript in your page #1 and provide link to page#2 inside page #1. Now when the user scrolls past page#1, the only variable that the plugin has is the current page number, like, 2, or 3 or 4 (N)
The plugin needs to create the URL to fetch content from when user is scrolling. So how does the plugin do that? The plugin looks at the next URL structure provided in page#1, parses it and creates a "base path" to which it will keep adding current_page_number to fetch subsequent content. That is the role of NAV selector.
So let's say I have something like /home/page/2 as next URL in page#1. The plugin will parse this into an array as
[/home/page/,2]
and think that base_path = "/home/page/"
when the plugin attempts to fetch page_number 3, it will just append 3 to the base path, like base_path.join(current_page_num) making it /home/page/3
On server side I can just have a controller that takes care of all the /home/page/1 to /home/page/N links. You can just look inside the plugin, look for _determinePath and retrieve functions.
Now you can see the problem as well. The problem is that there can be an infinite variety of URL structure depending on how you are doing pagination inside your code and how many variables do you need. My way of doing pagination is different from your way of doing pagination. Same holds for frameworks. Drupal pagination scheme may be different from Djanga and wordpress etc.
The plugin cannot possibly cope with all these URL structures. Given a next URL, it cannot possible always deduce the "base path" to which it needs to add current_page_number. Again look at _determinePath() method of plugin to see what kind of URL it can cope with. It can parse simple URL structures, like page2.html or page=2 but you have to provide your own implementation if your URL structure is complicated or something that the plugin cannot handle. Look at pathParse() method as well.
2)Is it possible to implement infinite scrolling with the same plugin if I dont know how many pages I will have.
Again, there is no need to create HTML files. You have two options to signal end of content (without knowing how many pictures you have in advance)
When you have reached the "no content condition" you can return an HTTP 404.
Or you can return an empty string.
Does this answer the question?
How it can work with the plugin
First page - include - NAV SELECTOR - LOAD THNIGS THE USUAL WAY
First page on load - use instagram pagination and store "nextURL" in your javascript somewhere
On Scroll - override _determinePath to provide your own fetch URL using (2) - let plugin retrieve that URL
Override plugin content selector - so it returns new elements to callback
On Plugin fetch content - Use the callback inside plugin to update your page
Update on github repo
I have forked paul's github repo to add documentation for PHP server side integration. I believe that plugin's assumption that next URL is only dependent on current page number is too restrictive. We need to get nextURL from next page content.
Github Repo - https://github.com/rjha/infinite-scroll
Pull request on base repo - https://github.com/paulirish/infinite-scroll/pull/219
My javascript knowledge is very limited and maybe you can do a better job of extending the base plugin. However every drop helps make the ocean :)

Does that mean this plugin (Infinite Scroll) requires to have "n" amount of html files in a directory to achieve infinite scrolling?
Yes, that particular plugin seems to be designed to support only static pages, which otherwise would use a "Next page" link. The tutorial you found even states that it could not handle dynamically generated content with URL-parameters, though I don't really believe that.
Is it possible to implement infinite scrolling with the same plugin if I dont know how many pages I will have. Even better without even having to create physical html files?
By design of that plugin I'd say No. Of course, you should be able to use an (unknown) amount of dynamically generated pages with the pictures. This needs serverside code to be fed from the instagram api, which does not seem to be what you want.
How can this kind of pagination is implemented? (i.e loading chunks of 20 pics as long as the user keeps scrolling down) there is not that much documentation online, could you provide a short step through demo or description?
There are other infinite-scroll plugins. The demos 2 and 5 on that site you found implement a simple "native" (i.e., no plugin) infinite scroll, both loading the new content via ajax. The demos 3 and 4 use the endless-scroll plugin with a few more scrolling options, although the demos do not include ajax.
Now you are free to decide how you would like to implement your script. You seem to want to get all image urls from instagram at first, but append (and therefore load the image files) only chunkwise. If instagram supports a paged api, you might want to combine both load processes.
This can be done with code like in the demos 2 to 5 - when the scroll reaches the page end, trigger your requests to load the images. After that happened, call Masonry's appended method on the new the img elements (or instaframe divs, like in your example).

Related

How do I "load" another HTML file?

Hey so I'm making some software that will have 4 different steps.
load
edit item 1
edit item 2
submit to an online storage
Since item 1 and item 2 are large items to be edited I wanted a separate page.
I also wanted a separate page to submit both items so they know it's being submitted and user receives further instructions.
I used to just let it just redirect the user to the next page, but I found it took 2-5 seconds to load each page, and I rather have it a fluid process.
Since Im using electron.js I am using require to load the JS part of the webpages.
But cant find a way to load the HTML and load the JS parts that effect the HTML (JS needs the webpage's DOM).
I've attempted using Jquery but all I accomplished was getting the html in a string format.
Been trying to find a way to use ajax, but so far everywhere I've looked its for including the html into a different html page.
I am new to both Jquery and ajax and just looked at them today. So maybe I am missing something about them. But cannot find any tutorials/documentary for loading another page.

Is it possible to direct which elements of a page are painted first by the browser?

I wanted to know if there was any way to control browser painting, for example I'd like to load elements at the top of the page first so users can see content straightaway. The elements at the bottom of the page can load last as the user will not see them until they scroll down.
I'm looking to optimize my site which currently has a 6 second load time and I'd like to get it down to 1 second. This is mostly being caused by JS and images. I know that reducing both these will mean I wont need to worry about directing the painting but out of interest I just wanted to know if it was possible?
Apologies if my understanding of browser painting is very basic
its not that difficult. all you need is ajax. load the inital markup and then load the rest of the page via ajax.
just load the page with little markup which you initally want to show to the user. then as user scrolls down you can make ajax calls and get xml or json or also html files and render them on you page, for example:
$(window).on( "scroll" , function() {
var $document = $(document);
var $window = $(this);
if( $document.scrollTop() >= $document.height() - $window.height() - 400 ) {
//make ajax call here and load the data
}
});
Also read this
After looking into this further I found this article
http://www.feedthebot.com/pagespeed/prioritize-visible-content.html
which provides a good way of directing which parts of the page are rendered first. By separating your content in to above and below the fold content you can decide what needs to be delivered first i.e. your main content rather than sidebar ads. Using inline style to display your above-the-fold content will make it appear very quickly since it won't need to wait for for an external request.
But this is only good for simple CSS, if pages require complex CSS then it's better to use an external file because:
"When you use external CSS files the entire file is cached (remembered) by the browser so it doesn't have to take the same steps over and over when a user goes to another page on your website. When you inline your CSS, this does not occur and the CSS is read and acted upon again when a visitor goes to another page of your website. This does not matter if your CSS is small and simple. If your CSS is large and complex, as they often tend to be, then you may want to consider that the caching of your CSS is a better choice."
http://www.feedthebot.com/pagespeed/inline-small-css.html

Looking for a demo website that uses the simplest form of re-use for multiple pages as possible

In teaching students in an intro web class, I want to find the most straight-forward way of building a multipage static site of about 7 pages without having them have to make 7 different pages.
Obviously, I can have them make a separate header, footer, and menu file, and use server side includes, and just put the includes onto 7 different pages of content - but that feels dirty.
In the past I had them doing it this way: http://www.tropicalteachers.com/web110/?Ignore_WEB_119_CLEAN:MX_-old_Extra_Credit:Dynamic_PHP - this was a quick experiment using the assignment as a model: http://www.yetirobotics.org/index2.php?pagename=team_yeti
but i feel like there should be a cleaner/simpler way to do it using javascript, or maybe in php - but i'm not sure of how.
Basically i'd like one main page with a menu -and when the menu items are clicked, it loads different content. I believe it's better to have the content in seven different files, but i could imagine it all being in the same JS within one page- remember, this site should be pretty simple.
I'd like to limit it to html/css/js/php, and preferably js OR php and not both.
with just the index page controlling (and loading) everything.
Thanks!
If you want to create a more modern framework then you should look into using javascript for displaying content dynamically (as you suggested in your question). To do this I would make use of a framework like jQuery as it makes asynchronous request calling far more simple. To do this you would code a single page with a specific area marked for the dynamic content.
Server side you would setup either pages or a database to return the main content area that will change upon request.
Client side you can use jQuery's load to place the requested content into the content area.
$('#contentArea').load('url', function() {
//callback area in case there is other stuff you want to do with js
location.hash = 'blah';
});
It would probably make sense to change the page's hashmark so that pages still seem static and are linkable as content changes.
location.hash = 'blah';
In addition you will need to override default link behavior by returning false when they are clicked.
myLink.click = function() {
$('#contentArea').load('url', function() {
//callback area in case there is other stuff you want to do with js
location.hash = 'blah';
});
return false;
}
I think this would be a good lesson for students as it shows the differentiation between client-side, server-side, and how to connect them dynamically via javascript.

General questions about #! hashbang urls and am I using them correctly

I'm in the process of writing a website that includes a reasonably large gallery. First page of the gallery the user will be displayed a bunch of thumbnail images with a url of: website.com/gallery.php
When they click a thumbnail image, if javaScript is turned off it will follow the url in the href and go to a page called gallery.php?img=67. If javaScript is turned on the href click will not execute, instead it will perform an ajax request to display the larger image and some text about it. The url changes to gallery.php#!img=67. The back button will take you back to the thumbnails, pressing f5 will keep the big image displayed with the text. If someone copies the address with the #! and sends it to someone they will get the same image displayed (assuming the receiver has javaScript turned on).
My question is, have I sorted this out correctly for google to index the individual gallery pages? Will google index them twice, once with the ?img=67 and once with the #! and if so is that a bad thing? I'm using javaScript/Ajax to preload the larger images once the thumbnail page is loaded for speed. I've read a lot of backlash against using hasbang ajaxy things recently and wondering if you think can justify using it here?
Google will follow your links and index the ?img=67 pages, and will not index your #! pages, because it can't see those links. You can tell Google about those links by doing the following:
Add <meta name="fragment" content="!"> to the <head> of your document, and
Handle requests for /?_escaped_fragment_= by returning an "HTML Snapshot" of your page that has all your #! links in the <A> tags.
Also, to make the most of this feature, you should also handle requests for /?_escaped_fragment_=img=67 by returning an HTML snapshot page with the big image displayed. Remember, GoogleBot doesn't execute Javascript. Using the #! URL tells Google to retrieve an alternate version of the page (A version where #! has been replaced with ?_escaped_fragment_=) that should render without Javascript.
THe use of #! tags in URLs are in the news recently, with updates to a well known blog.
http://isolani.co.uk/blog/javascript/BreakingTheWebWithHashBangs has a good description of what they are best used for - and when they can be bad. I think your use in a gallery is quite valid.
In short, a URL like http://lifehacker.com/#!5753509/hello-world... is rewritten by Google, and other compatible web-spiders as http://lifehacker.com/?_escaped_fragment_=5753509/hello-world...
Google may index them twice, but you can also use the canonical meta-tag to ensure it knows what the 'official' copy is.
Possible solution (as suggested in http://isolani.co.uk/blog/javascript/BreakingTheWebWithHashBangs) is to use regular links and translate them to #! in the OnClick() event. This ensures that the site displays regular links and not the shitty #!.
It does mean extra work for the server though, since the server needs to support both versions (the Ajax version and the regular version), but I think it worth it.These #! are so ugly..

how load some js(or any other) files dynamically & indicate percentage of loaded data?

I've a html page which must load many heavy js files at the begining. It usualy takes a lot to load all of them & user can`t see how much of these data is loaded & how much has remained!
So i need to add a simple progress bar using javascript(I mean some way to indicate amount of loaded & remaining data, the graphical presentation is not important at all, it can be as simple as a number between 1 to 100!)
I need something like this pseudo:
var filesToLoad = ['jsFilepath/s1.js', 'jsFilepath/s2.js', 'jsFilepath/s3.js'];
showProgressBarAndBeginLoadFiles(filesToLoad);
Any idea ?
You could put ten calls to a JavaScript function like updateProgressBar(percentage) through the files s1.js, s2.js s3.js. In updateProgressBar function you could fill div with some indicator of the current status of the JavaScript load. Not the cleanest way to do it but I think it would work. Not sure if you are able to add stuff to s1.js, s2.js, s3.js in your example.

Categories