Hi all. Today I want to talk to you about how to organize content lazy loading on landing pages.

Often, it is also called "infinite scrolling". Surely you have seen a similar effect when the content is not initially present on the site, and as the page scrolls, it smoothly loads.

A long time ago, they wrote to the “Your Suggestions” section with a request to write an article on how to implement such an effect:


So I decided to start implementing. Thanks for bringing up ideas. Let's get started...



As in most cases, we start by including the jQuery library:

And now you need to digress a little and I will explain to you the essence of the method. All this is started in order not to load all the elements of the site (your portfolio or reviews), but to load them as needed. For example, when the user clicks on the "Show more" button. Thus, the page will load much faster. And now the essence, with the help of ajax technology, we will load the desired element (div) and third party file to our landing page. Everything is so simple, both in theory and in practice, and you will soon see this.

Now let's create the main block, for example, with pictures of our work. Suppose we draw icons, and we will load them when the button is clicked. I created a structure like this:

Portfolio

Show more...

As you can see, everything is simple. But what should you pay attention to? And you need to pay attention to the div with id="smartPortfolio", id="moreButton" and id="loadingDiv", as they are used in the script, which helps us to load content from other pages. SmartPortfolio is a "container" for our portfolio. MoreButton - this will be our button, when clicked on, another part of the portfolio is loaded. LoadingDiv - the area in which the text will be displayed when the portfolio is fully opened, or some kind of error occurs.

For example, some of the readers will still try to test this script not on the server, but simply open the index file in the browser. In this case, they will see an error message. In addition, at very slow connection, it may take time to download files, and so that the user understands that the process is in progress, you can enter a message there that data is being loaded or put (a picture, a progress indicator, or something else).

I didn’t write the script myself, but I found it on one of the sites, the author is listed in the source code, for those who are interested, take a look. Since it is not too large, I will give it all, but if you plan to use the same ID names and file paths as mine, then you can not even look into it, but simply include it before the closing body tag (in the footer) .

For those who plan to make changes, here is the script itself:

var lazyload = lazyload || (); (function($, lazyload) ( "use strict"; var page = 2, buttonId = "#moreButton", loadingId = "#loadingDiv", container = "#smartPortfolio"; lazyload.load = function() ( var url = "./pages/" + page + ".html"; $(buttonId).hide(); $(loadingId).show(); $.ajax(( url: url, success: function(response) ( if ( !response || response.trim() == "NONE") ( $(buttonId).fadeOut(); $(loadingId).text("Portfolio is fully loaded"); return; ) appendContests(response); ), error : function(response) ( $(loadingId).text("Sorry, something went wrong with the request. Please refresh the page."); ) )); ); var appendContests = function(response) ( var id = $(buttonId); $(buttonId).show(); $(loadingId).hide(); $(response).appendTo($(container)); page += 1; ); ))(jQuery, lazyload) ;

So, now it's worth talking about those files from which we will load information. The script assumes that these will be files with names 2.html…5.html, etc. which contains our information. For example, my 2.html file is loaded first and it has the following content:

In my site structure, the pages from which information will be taken for subsequent loading when clicked, lies in the pages folder. There are three files, two of which are full, and the last one is empty. It assumes the logic of the script.

The path in the script is specified as follows:

Var url = "./pages/" + page + ".html";

If you plan to use a different path, be sure to replace it in the script. In addition, if you used other IDs, then they will have to be redefined in the script. Right here:

ButtonId = "#moreButton", loadingId = "#loadingDiv", container = "#smartPortfolio";

And, as I said, before the closing body tag, we include the script itself:

Like this on landing page You can implement lazy loading. Send more topics on which you would like to read an article on the blog. As far as possible, I will try to publish not the planned material, but the one you ask about in the “Your Suggestions” section. And for today, that's all. Bye!

AJAX and jQuery. Dynamic content update. Basics (changes from 01/03/2012)

This article will discuss what AJAX and jQuery are and will look at examples of how to use them.

AJAX is a tool for building web applications that communicate with the server in the background. In this case, the user receives an application with a dynamic content update, without reloading the entire page.

jQuery - JavaScript-framework, a library that allows you to more conveniently use some of the features of Javascript, such as: creating visual effects, event handling, DOM manipulation, and AJAX support.

Download latest version jQuery and learn all the features in detail on the developer's website: http://www.jquery.com/

In this article, we'll only be looking at one function in the jQuery library, namely the $.ajax() function. This feature allows us to both send data to the server and receive responses from the server, all in the background, without reloading the page. The setting for receiving or transmitting data depends on the parameters with which the $.ajax() function is called. The main ones will be discussed below. You can read more about parameters in the jQuery manual.

Let's move on to examples.

Important!
In order for the examples to work correctly, you must:
1. All files must be written in UTF-8 encoding.
2. Scripts must be run on the web server, not run in the browser as a file.

Example 1: Dynamic content update on a timer

Let's create a simple program that displays current time, updated once per second by timer. A feature of this program will be getting information about the current time from another external file.

The content of the index.html file.

There are several features in the code, let's explain them.

1. The jQuery library is included in the header HTML file, this line is written for this.

The jquery.js file itself is located in the same folder as the example files.

2. A container is created in the body of the document into which we will load the content.

3. Strange at first glance, the $(document).ready() function is required for the correct jQuery works, besides, in it we can perform all the preparations for the program to work. In our case, we call the show() function, which has a mechanism for getting content from another file, and set up a timer so that the show() function is called once per second.

$(document).ready(function()( show(); setInterval("show()",1000); ));

4. The show() function consists of a call to the $.ajax() function with a certain number of parameters, which allows us to get information from an external file on the server in the background.

$.ajax(( url: "time.php", cache: false, success: function(html)( $("#content").html(html); ) ));

Consider the parameters of the $.ajax() function used.

Url: "time.php" Refers to the time.php file to get the content. cache: false Query results are not cached. success: function(html)( $("#content").html(html); ) If the request succeeds, control passes to a function that receives the content as a parameter and writes its container. Writing to the container occurs in this line:
$("#content").html(html);

The contents of the time.php file.

The purpose of the time.php file is to display the current time on the screen.

Download source files example (16.6 kb):

Example 2: Dynamic content update based on the user's choice

A program that dynamically loads content of the user's choice.

The content of the index.html file.

What page would you like to open?

In the body of the document, a form is created that has two buttons, through which the user selects the desired content. And a container for loading content.

The page 1 button click event is handled by the $("#btn1").click() function, and the page 2 button click event is handled by the $("#btn2").click() function.

The contents of the page1.html and page2.html files that are dynamically loaded into the content area are simple html pages or text files with content.

Download sample source files (18.4 kb):

Example 3: Sending data to the server in the background and getting content

Consider an example that sends the entered username to the server. The server, when receiving a name, issues a greeting and counts the number of characters in the entered name.

The content of the index.html file.

Enter your name:


A form for entering a username has been created in the body of the document. And a container for loading dynamic content.

Note that the form itself does not have the usual action and method fields. The $("#myForm").submit() function acts as the event handler for clicking the "Submit" button. Let's consider this function.

$("#myForm").submit(function()( $.ajax(( type: "POST", url: "greetings.php", data: "username="+$("#username").val( ), success: function(html)( $("#content").html(html); ) )); return false; ));

As we can see, the main work is again related to the $.ajax() function. This time they appear Extra options, not considered in examples 1 and 2. Namely:

Type: "POST" Type of data transfer. data: "username="+$("#username").val() Parameters passed to the server. In this case, we are passing the contents of the username field - the username. In general, the parameters are written in the same way as in GET method, in one line, for example:
data: "username=Vasya&age=18&sex=male"

Note that at the end is written the line:

return false; This is done so that the form does not try to transfer data to the file from which it is launched and the page does not reload.

Contents of the greetings.php file.

".$_REQUEST["username"]."!
"; echo "Your name has letters: ".strlen($_REQUEST["username"])."."; ?>

We display a greeting on the screen and count the number of characters in the name.

Download sample source files (16.8 kb):

It should be said in conclusion that in addition to the obvious advantages of creating pages using dynamically updated content, there are a number of disadvantages that should be considered when developing a site, namely:

1. On pages with dynamic content updates, the "Back" button in the browser does not work correctly.

2. Pages with dynamic content updates don't change URL based on their content, so they can't be bookmarked.

3. Pages with dynamic content updates are not indexed search engines, because they do not execute JavaScript commands.

These shortcomings can be eliminated programmatically. This article does not cover such methods.

It's been a while since I posted any code. Today I will correct the situation and give some useful jQuery snippets that you will definitely need on your sites.


I will not go into theory, all jQuery documentation is on the official website of the library. I'll just remind you what jQuery is.

jQuery is JavaScript library focusing on JavaScript interaction and HTML. The jQuery library makes it easy to access any DOM element, access the attributes and content of DOM elements, and manipulate them. The jQuery library also provides a convenient API for working with AJAX.

So let's go!

1. Smooth scrolling to the top of the page

No website is complete without it. Just 4 lines of code will allow your visitors to smoothly scroll the entire page up in one click.

$("a").click(function() ( $("html, body").animate(( scrollTop: 0 ), "slow"); return false; ));

2. Duplicate table headers

To improve the perception and readability of your tables, you can duplicate their titles below the table. It would seem a trifle, but it is very convenient in complex and large tables that do not fit on one screen.

$tfoot = $(" "); $($("thead").clone(true, true).children().get().reverse()).each(function()( $tfoot.append($(this)); ) ); $tfoot.insertAfter("table thead");

3. Loading external data

FROM jQuery It is very easy to upload external content to web pages. It can be displayed directly in a DIV block, as in the example below.

$("#content").load("somefile.html", function(response, status, xhr) ( // error handling if(status == "error") ( $("#content").html(" An error occured: " + xhr.status + " " + xhr.statusText); ) ));

4. Equal column height

It is known that to align the blocks in height standard means HTML and CSS is not so easy. Just a few lines of code below will allow you to make the height of all blocks equal to the height of the larger block.

varmaxheight = 0; $("div.col").each(function()( if($(this).height() > maxheight) ( maxheight = $(this).height(); ) )); $("div.col").height(maxheight);

5. Tabular zebra

As you know, the perception and readability of the table will be noticeably higher if you make multi-colored row alternation. This is very easy to implement with jQuery.

$(document).ready(function()( $("table tr:even").addClass("stripe"); ));

6. Partial page refresh

With jQuery it is very easy to implement a block (partial) page refresh. For example, the code below will allow you to automatically update the #refresh block every 10 seconds.

SetInterval(function() ( $("#refresh").load(location.href+" #refresh>*",""); ), 10000); // milliseconds to wait

7. Image Preload

This code allows you to load images in the background without loading while viewing the page. Just list in line 7 the images you need to preload.

$.preloadImages = function() ( for(var i = 0; i ").attr("src", arguments[i]); ) ) $(document).ready(function() ( $.preloadImages("hoverimage1.jpg","hoverimage2.jpg"); ));

8. Opening external links in new windows/tabs

This snippet forces all external links on the page to open in a new browser window. The script tritely determines the current domain of the site, and works if it does not match the address in the link.

$("a").each(function() ( var a = new RegExp("/" + window.location.host + "/"); if(!a.test(this.href)) ( $(this ).click(function(event) ( event.preventDefault(); event.stopPropagation(); window.open(this.href, "_blank"); )); ) ));

9. Block in the entire browser window

This script will help you stretch the block to fill the browser screen. Great for modal windows and dialogs.

var winWidth = $(window).width(); var winHeight = $(window).height(); $("div").css(( "width": winWidth, "height": winHeight, )); $(window).resize(function()( $("div").css(( "width": winWidth, "height": winHeight, )); ));

10. Password complexity check

If you allow visitors to your site to set their own passwords, it would be a good idea to control its complexity and inform the visitor about it.

First, let's write the HTML part of the code:

And with the help of the code below, we will check the entered password and display information to the visitor: his password is complex, medium or weak, and also check if it is too short.

$("#pass").keyup(function(e) ( var strongRegex = new RegExp("^(?=.(8,))(?=.*)(?=.*)(?=.*) (?=.*\\W).*$", "g"); var mediumRegex = new RegExp("^(?=.(7,))(((?=.*)(?=.*) )|((?=.*)(?=.*))|((?=.*)(?=.*))).*$", "g"); var enoughRegex = new RegExp("( ?=.(6,)).*", "g"); if (false == enoughRegex.test($(this).val())) ( $("#passstrength").html("More Characters "); ) else if (strongRegex.test($(this).val())) ( $("#passstrength").className = "ok"; $("#passstrength").html("Strong!" ); ) else if (mediumRegex.test($(this).val())) ( $("#passstrength").className = "alert"; $("#passstrength").html("Medium!") ; ) else ( $("#passstrength").className = "error"; $("#passstrength").html("Weak!"); ) return true; ));

11. Image resizing with jQuery

Of course, it is more logical to resize images on the server side using PHP and GD, but there are situations when this needs to be done on the client side. And jQuery will help us with this again.

$(window).bind("load", function() ( $("#product_cat_list img").each(function() ( var maxWidth = 120; var maxHeight = 120; var ratio = 0; var width = $( this).width(); var height = $(this).height(); if(width > maxWidth)( ratio = maxWidth / width; $(this).css("width", maxWidth); $(this) .css("height", height * ratio); height = height * ratio; ) var width = $(this).width(); var height = $(this).height(); if(height > maxHeight)( ratio = maxHeight / height; $(this).css("height", maxHeight); $(this).css("width", width * ratio); width = width * ratio; ) )); //$( "#contentpage img").show(); // IMAGE RESIZE ));

12. Loading content when scrolling down the page

This technique is often referred to as infinite scrolling. Content is loaded as the user scrolls the page. This is easy enough to implement with the code below.

var loading = false; $(window).scroll(function()( if((($(window).scrollTop()+$(window).height())+250)>=$(document).height())( if( loading == false)( loading = true; $("#loadingbar").css("display","block"); $.get("load.php?start="+$("#loaded_max"). val(), function(loaded)( $("body").append(loaded); $("#loaded_max").val(parseInt($("#loaded_max").val())+50); $ ("#loadingbar").css("display","none"); loading = false; )); ) ) )); $(document).ready(function() ( $("#loaded_max").val(50); ));

13. Verify image upload

It often happens that you need to check whether an image is currently loaded or not. And jQuery will help us with this again.

Var imgsrc = "img/image1.png"; $(" ").load(function () ( alert("image loaded"); )).error(function () ( alert("error loading image"); )).attr("src", imgsrc);

14. Sort alphabetically

If you need to dynamically sort a list alphabetically, this little snippet will definitely help you.

$(function() ( $.fn.sortList = function() ( var mylist = $(this); var listitems = $("li", mylist).get(); listitems.sort(function(a, b) ( var compA = $(a).text().toUpperCase(); var compB = $(b).text().toUpperCase(); return (compA< compB) ? -1: 1; }); $.each(listitems, function(i, itm) { mylist.append(itm); }); } $("ul#demoOne").sortList(); });

Save - useful.

All the latest and most interesting from the world of WordPress in my Telegram channel. Subscribe!