Loading contents dynamically - javascript

I have product listing page, which displays all the products which satisfy the search criteria. And these could be any number of products.
What I want is something like FB, that I display only first 5-7 products and as the user scrolls down, the products should be loaded dynamically.

I'd consider switching to jQuery or Mootools as JS libraries if you want to do this - both have native support for the infinite scroller concept as it's commonly called. It's not that hard to implement yourself though, mainly a matter of keeping track what you loaded last, and installing an onScroll event to detect when the bottom of the page is reached.
Here's a good tutorial using native JS to implement it, both server and client side. You'll need to replace the XHR invocations by the proper Prototype alternatives yourself (or not, wouldn't really matter).

Related

Automatically Load All Webpage Data/Automatically Scroll to End

Take https://www.instagram.com/instagram as an example. If you click on 'Followers', a list of all the followers is loaded, but only a few are loaded at a time, and you need to continually scroll until all data is loaded.
Is there a way in Javascript to automatically load all the data, or maybe even automate the scrolling for that particular div?
Thanks.
A few things to consider.
The method Instagram is using to show some followers until you scroll to get more is called Infinite scrolling.
Basically, all we have to know is that this method is implemented on the client, that is, in the browser, using JavaScript.
The first solution is: if you can reverse engineer the Instagram code (minified I suppose) and find the good methods to call, you can force fetch new items even if you didn't scroll.
On the other hand, another technique would be to constantly simulate a scroll to the end, I let you refer to this answer on how to.

Performance issues in large jQuery Application

I have a web application which has 8 tabs on the menu. When I click on one tab the current content fades out and the content specific to tab comes up.
This thing is working all fine but the application is pretty slow as the fadeIn and fadeOut is being done on very large html (maybe around ~2000 lines/tab of ) content which is inturn making the whole application slower.
What can I do to make it snappy and smooth.
Here are some doubtful points I have...
Can I load the tab content via AJAX instead of loading all of them in one go?
If I load them via AJAX for ex of Tab A and then user clicks on Tab B, should I remove Tab A content from the DOM and reload it on click of Tab A Again or should I keep it in the DOM.
What will happen to the click handlers as I need to do dynamic event binding in that case.
What else can be done in order to enhance the performance?
Thanks a lot!
Well, we had that kind a problem, where we have around 10 tabs and need to load data. The doubts you are having is already turned to solution. I ll define wat we have done to accomplish the task with more smooth and perfect result
We are binding the data on tab click using Ajax call, rather than making elements on the runat server. We are binding it on client side Dom manipulation.
If there is a grid, that will have large set of amount, binding data for evey pagination, rather to load whole set of data.
On every tab click data is loading and data on previous tab is cleared. Or into its default position.
If large set if data remain on html, so Dom will Also be heavy and which in turn slower your application.
5.for this task to accomplish you have to create Ajax calls and more Dom.manupulation , which will inturn take more time. So have to decide the path in which direction you want to go.
From my standpoint , there are some observations. I can think if to enhance the performance of the application.
Check if there are any heavy image which will take time to load or slower down you page to compete all loading
Remove the reference of any unused js file or CSS.
User of async and defer with external scripts.
Try not to use more server side element which overhead your page to load, because they gonna bind on server side. Which makes you page heavy.
In some cases compression techniquie is also helpful for me.
Ajax calls and client side manipulation is best, rather to send whole page on server side. !!!
From my experience, these are the things I learned and implement when working with web application to improve the performance of the application.

Infinite scrolling using AJAX, Javascript/jQuery, the DOM and Facebook Like button

I am preparing to implement a Twitter-like infinite scrolling to my product pages. That is, loading additional page portions using AJAX when I am crossing certain scroll thresholds. But I am unsure how the topics in the title are affected after such loading. My questions are the following:
For each new batch of elements being loaded with AJAX, will the DOM be updated for these new elements OR totally renewed? What happens with the old DOM?
Will I be able to use Javascript and jQuery on these new DOM elements exactly like I have on the DOM I start off with for the page? I guess this relates to the first question.
For each load, I will load say 9 new products. Each product has a FB Like button which is utilising FB Open Graph API. Will the new products Like elements go through the same asynchronous modification which happens to the DOM elements I start off with so that a proper Like submission is possible?
Let's begin one by one.
The DOM, in your intent, should only be updated, not renewed. There
is no old DOM since what you do is to insert new elements on them.
Yes, you'll be able to do that. Be careful though with event
listeners because if you start them wrong, you'll have to attach new
event listener to those new nodes again. For example:
$('body').on('click','a.addToCart',function(){}) // Will match present and future nodes
$('a.addToCart').on('click',function(){}); // Will only match present nodes
Yes, you'll need to do the same process for each button again.
Bonus tip: If you care about mobile environments, you should keep your DOM as clean as you can by deleting nodes you won't need.
Just use document.appendChild() for adding new Elements to the DOM. (http://www.w3schools.com/jsref/met_node_appendchild.asp)
Rebuilding the hole page would be a waste of time ;)
There should be no problem. I've done it many times without any problems. If you are using jQuery Mobile you have to refresh the new elements maybe. (Look at the methods of die jQuery Mobile Widget you are using, if it needs refreshing)
I don't have much experience with the facebook api, but i would say "yes" =)
edit: I had a link to a german site in my answer. I've forgot that this is an english site ;)

AJAX - Element / Class / Timer cleanup on replacing content

As many developers will be I'm producing web based application that are using AJAX to retrieve data and HTML.
I'm new to web development and javascript but have a couple of decades experience in programming in other languages.
I'm using mootools, which is a great framework, but have been battleing with the lack of destructors in javascript or even onDestroys/ unloads for the dom elements.
I've written a number of UI classes ( mostly to learn ) and alot of them use setInterval timers to periodically get data from the WebServer and update elements on the page (mostly images from cameras).
Most issue occur when another page is requested with the menu and the content div is reloaded with new HTML and Javascript ( using Request.HTML ). This simple replaces all the elements already in the div with the new one and runs the new scripts. Any timers in the old scripts or old objects created will continue to run. This was leaving me with lots of orphaned Clases, elements and timers.
I've been reading more on the mootools site and have realized a number of mistakes I've been making and have started to correct alot of the issues. The biggest of which was not using Element.store and Element.retrieve instead of linking my classes directly to the Elements.
I've already found that the contents of the div being reloaded need to be freed by calling destroy on all its child elements before calling the Request.HTML but that will not remove (clear) any timers that are running.
So I've done a JSFiddle here deinitialize classes to show what i've been trying, its appears to work fine but the following and what i want to know is,
Is it a good idea?
are there any other issues I might have missed?
can you see any problem with this type of implementation ?
or am I reinventing the wheel and missed
something?
Explanation
When the class is initialized it stores itself with the element.
It also appendes (makes if necessary) itself into an AssocClasses array also stored with the element.
I've created a ClearElement function that is called whenever the contents of an element are to be replace with and AJAX call or other method, which gets all elements within the div and if they have and AssocClasses array attached, calls the deinitialize on each of the Classes in the array, then it calls destroy on each of its direct children to free the elements/storage.
Any information, pointers etc would be most greatfully recieved.
Most issue occur when another page is requested with the menu and the content div is reloaded with new HTML and Javascript ( using Request.HTML ). This simple replaces all the elements already in the div with the new one and runs the new scripts. Any timers in the old scripts or old objects created will continue to run. This was leaving me with lots of orphaned Clases, elements and timers.
I would rethink your timer storage and use of evalScripts in your ajax calls.
Keep these outside of your AJAX requests. When doing peer code reviews rarely have I seen an instance where these were needed and could be done in a better way.
Maybe on the link that is clicked have it trigger a callback function on Complete or onSuccess
Without seeing your exact code it will be hard to advise further.

MVC-like UI updates in Javascript/jQuery: best practices?

I'm coming across a bit of an awkward problem. I have a Web page with quite a few buttons on it that need to be disabled and enabled at various points. Now if this were a Swing (or any otehr desktop UI interface for that matter), it would be quite trivial: I would simply add listeners for the model changes I was interested in and update the UI accordingly.
This is basic MVC stuff really.
Thing is, I'm at a bit of a loss as to how to handle this nicely in Javascript. I'm going down a route that will end up with some real spaghetti code where the click listeners for the buttons are updating the UI controls and that's just not going to end well.
EDIT: Let me give you a more concreate example.
Example
Imagine a screen that lists open orders. Those orders are presented in a table as each row (order) has multiple attributes against it, such as who is currently managing the order, who made the order, what it's for, when the order was made and the status of the order.
I've done it so you can select one (or more) of these orders by clicking on the rows. This adds a "selected" class, which changes the styling, much like a list.
As to the behaviour, if a user selects one order then certain actions become available, such as Open Order (to view the details), Take Owneship, Cancel and so on. The attributes of the order may also affect what actions are available eg if the order is "owned" by somebody else already, certain actions will be disabled.
Some of these options (like opening the order) aren't available if you've selected multiple orders.
Additionally via a background Ajax call the list refreshes with new orders periodically. The user can also click refresh or can filter the orders (by name, date range and so on) and then reload the orders. While the orders are reloading certain buttons get disabled.
I was going to do a second example but I think that one is sufficiently complex to illustrate the kind of problem. Now I've started this by giving various controls classes. For example, elements with the "select" class might be disabled/enabled/styled when an item is selected.
Now this works reasonably well in simple cases but I'm running into problems where the state of a control depends on multiple conditions. Also the classes are getting fractured by things like some elements want to be styled, some controls want to be disabled/enabled and in some cases both things need to happen.
In Swing I tended to handdle this kind of thing by having a sort of updateUI() method, which would be called whenever the state of a relevant control or model was changed. It would then set the state of all the controls explicitly. Now this is arguably not the most efficient way (eg if you have 30 controls and only need to update one of them it's a bit of a waste) but I found the simplicity was worth it. The alternative was that controls/models ended up with too information about what controls they depended on or those that depended on them. It go tmessy from a coupling point of view.
But I have no such (obvious) mechanism in Javascript. Inobtrusive Javascript as advocated by jQuery is great because it stops random code snippets being littered throughout your code. But I need to go a step further nad have some way of managing the complexity of this (because it is quite a complex screen and will only get more complex).
If you want to preserve your sanity, use a state machine.
You don't really give details about what your UI does, so I'll make up an example. Let's say you have a file upload page. The user should be able to select a file, click an upload button, and then be returned to the page they came from, when uploading is complete. So you could have three states, "SelectFile", "Uploading", "Finished". In the "SelectFile" state, controls should be enabled to allow the user to select a file. In the "Uploading" state, these control should be disabled, and the user should see a progress indicator. In the "Finished" state, the user should be redirected.
Of course, it sounds like your case is more complicated, but the same ideas will apply. You may need more than one state machine, if portions of user interface interact. That's fine.
When you want to change the enabled/disabled elements on the user interface, you just change the state of the state machine. The state machine itself tells the various user interface controls to update themselves based on the current state. You can use a Bharani's (good, up voted) suggestion of using classes to do this. Or whatever mechanism works for you.
The nice thing is that the controls no longer interact with each other. They only interact with the state machine. So you get rid of all the cases where states bounce around incorrectly or endlessly recurse.
Assign specific class names to the divs. That way even if they overlap in functionality you can simply keep adding class names to the div and because of the chain nature of jquery all registered event handlers will be executed.
For controlling form elements during ajax call - you can add ajaxStart and ajaxEnd or you can use ajaxComplete and handle all your code inside the callbacks.
I think i get your problem. I have worked on such screens before and i always ended up refactoring to structure the code better. But at times it will be easier if you could re-organize the functionality itself so that you don't have to handle all things in one place. I think GUI should also be treated like a function - do one thing and one thing well.
I think data modeling is important for JavaScript apps. I am working on this scheduling project for medical clinics and I have a JSON data structure that models chairs/patients in an office. Ember updates the views (UI widgets) automatically when the business logic changes in the models. So right off the bat a lot of sphagetti code is eliminated. If you are doing something graphically intense with user interaction it is almost a crime not to use an existing MVC pattern or to create your own MVC JS classes. The structured discipline is off putting at first but when you see later how it lowers your blood pressure and makes maintenance so much more enjoyable it is worth it. I wouldn't use it for simple one-off projects if they are small. It is better for medium complexity or advanced complexity. Anything that will take me more than a week I will use Ember. I have used knockout.js and Angular and I really like Ember with its Handlebars templating syntax. Easy on the eyes and efficient.

Categories