📜 ⬆️ ⬇️

6 tips for creating complex AJAX sites

We all know the many advantages of using AJAX: users do not need to wait for a new page to load, actions are performed in the background, and as a result, a much more dynamic user experience can be provided. Ideas seem to be simple, but creating a complex AJAX web application is hard enough. I created my blog based on AJAX, I have some tips and I want to share my experience with you. I hope I will help you get rid of some problems in the future!

Use event delegation


The main feature of AJAX sites is the use of event delegation. You should not assume that the element exists on the page (because it may have been contributed via AJAX), you should never try to assign event listeners (actions) directly to elements (other than document.body). Instead, the best solution is to use event delegation. Here is a very simple example of how to use delegation with jQuery:

// Add event listener to the body because it is a constant jQuery("body").on("click", "a", function(event) { event.preventDefault(); // Trigger the XHR to load the page content // ... // Update the History with pushState // ... // Other tasks // ... }); 

During the creation of my site, I wrote my code as if none of the elements except <body> existed. As a result, it took me less than 30 minutes to implement paginated AJAX navigation. Event delegation enables AJAX to load pages.
')

Use Pub / Sub for alarm events.

From the first - Signal events (Signal Events), for example, click on the link.
Implementing a publish & subscribe system gives your application a lot more options. If you are not familiar with pub / sub , imagine how the radio works: radio broadcasts ( publish ) and does not know who is listening to it. Listeners can listen ( subscribe ) without having any relation to the station itself.

I will show an example from my site to explain why and how you could use pub / sub . For any article, I want the first, download widgets of popular social networks, and second, show the rating widget so that users can evaluate the usefulness of the article. In a more static site, you would simply run the code to create these widgets in DomContentLoaded . On a complex AJAX site, these functions may have to be performed several times, so we will need a signal to change the page to recreate these widgets.

 // In the method where we do the AJAX request for new page content.... jQuery.ajax({ url: event.target.href }).done(function(data) { // Place the content in the page // ... // Send a pub/sub signal that the page is ready so that widgets can be created publish("/page/loaded", data); // Arguments are the channel name and data }); // ... Elsewhere, where the we set up the social widgets.... subscribe("/page/loaded", function(data) { // Set up the widgets! createSocialWidgets(data); // Fade in the widgets // ... }); // ... Elsewhere, where the we set up the rating widgets.... subscribe("/page/loaded", function(data) { // Set up the widgets! createStarRatingWidget(data); // Fade in the widget // ... }); 

In pub / sub, it's good that our JavaScript modules are separate from AJAX parts and we don't have to deal with massive callbacks. One call to publish and we allow any module to subscribe ( subscribe ) and respond to this event!

Use a single pushState manager


Complex AJAX sites do not just upload new content, they also change URLs using the HTML5 History API.
Popular jQuery plugin for pjax history.

It is important to ensure that the browser history is synchronized with AJAX page loads so that users can update, bookmark or share the URL of the current page with friends. It will also ensure the correct operation of the buttons back and forth in the browser!

Place notifications in a permanent place.


One of the possible problems encountered by users, they do not see the download status in the browser bar, it can be stopped by placing a notification (spinner) in a specific place on the page. It is important that users always know when processing is happening, and this is especially important when loading and rendering content happens dynamically!

Cache URL Query Results


From the web, you do not want more requests than you need, and this is especially true when you request a page completely. Creating a caching system for an AJAX site is (usually) much easier than you think:

 var cache = {}; // ... // ... within the AJAX callback cache[url] = data; // ... // ... within the click callback that would set forth a request if(cache[url]) { // Explicitly call the callback, passing it the cached page data return successCallback(cache[url]); } else { // ... do all of the AJAX request and callback stuff } 

This cache will not be used if the user clicks on the link several times, but it will be used if the user presses the buttons back and forth. Your server and users will thank you for caching on the client side!

When not to use AJAX


Not every page should load through AJAX, and it’s very important that developers can determine when using AJAX is problematic. In many cases, the results in the form should not be stored in the cache or be dynamically selected. There may be scenarios in which your infrastructure will suffer from AJAX loads. If you can define URLs that should not be loaded using AJAX, you can change the jQuery selector:

 jQuery("body").on("click", "a:not(href$='/some/page')", function(event) { }); 

You can add more logic within the callback for placing URLs. If when clicking a URL matches, you can not call preventDefault() and just allow the page to load normally.

When you plan for flexible code in advance, creating an AJAX site is easier than you think. Remember the tips from this post and 80% have already been done. Of course, some features will be specific to your site, but they will be insignificant in relation to the entire application. Happy AJAXing!

Source: https://habr.com/ru/post/198330/


All Articles