Dynamic web page refresh

image

Introduction


You will no longer be surprised by the concept of dynamic HTML, almost all sites have long been using javascript to one degree or another to make pages interactive. And with the advent of AJAX technology, it became possible to generate server requests asynchronously in order to change old data on the server or to receive new ones. But how exactly to update the page structure? Who should generate the new html server or javascript? Or maybe all together?

Let's see how these questions can be answered.

To get started, I will describe the life cycle of a page. I must say right away that I am not going to describe this process thoroughly, it only requires an understanding of the basic logic of the process.

Any web application can be logically divided into two components - the client part and the server part. The client part includes the browser itself and the scripts that it runs, the server part - a set of scripts that generate a response to any user request.

The life of any page begins with a request from the client to the server. The answer is a page code that contains, in addition to structure and styles, the logic of the client part.

After receiving the page from the server, the browser displays it and launches the scripts attached to it for execution.
The client part responds to various events - for example, when a user clicks on an element, moves a mouse, or expires in a timer. In order to receive some data from the server (or send something to it), additional, usually asynchronous, requests are used.

Piquancy begins when you need to at some point redraw some components on the page. In order to update the page structure, the client script needs to know what needs to be removed, what and where to add, what to replace. This is where various options appear, how to organize such updates.

Closer to the point


For ease of explanation, consider the option of updating a simple page with a news feed and, say, a follower counter. We want the browser to regularly check for feed updates, adding news as they become available. We also want every visitor to see the growth dynamics of our site - let the subscribers counter also be regularly updated.

The body of our page may look, for example, like this:

Подписчиков: 42

Option 1 - Duplication


The main idea is that both the client and server parts know the display logic. In this case, responses to regular requests from the client may contain only data - changes in the model, and look, for example, like this:

{
  subscr_cnt: 44,
  news:[
    {
      href: "/wiskey",
      name: "Названы лучшие в мире сорта виски 2015 года"
    },
    {
      href: "/kindergarden",
      name: "В Нью-Йорке появился детский сад для взрослых"
    }
  ]
}

Upon receiving such an answer, the client part “wraps” the data in html tags, adds the necessary texts and updates the page structure.

The server, on the other hand, needs knowledge about the display only in order to generate the initial version of the page.

Advantages of the approach:
  • Low traffic volume - only necessary data is transmitted;


Cons of the approach:
  • It is required to duplicate the code - it will be in the client part and in the server part;
  • The client part should know how to deal with each piece of data from the server — sometimes you need to replace the html of an element, sometimes add new data to an existing code;

Option 2 - Almighty Server and Fat Answers


The main idea is that only the server knows the display logic, the client part receives the ready-made html-code of the elements. Here the server response looks like this:

{
  subscr_cnt: "Подписчиков: 44",
  news: "
  • Крупнейшие на Земле метеоритные кратеры случайно нашли в Австралии
  • \n
  • Чудо-женщина ответила на критику о своей груди
  • «Ромео и Джульетту» экранизируют в духе «300 спартанцев»
  • Названы лучшие в мире сорта виски 2015 года
  • В Нью-Йорке появился детский сад для взрослых
  • " }

    I note that all html of each component on the page is forwarded here. But this method is implemented simply: the server generates a page in pieces, when the client receives a response, it replaces the bodies of individual elements.

    Advantages of the approach:
    • Ease of implementation;
    • No code duplication;


    Cons of the approach:
    • Multiple generation of the same code is especially inefficient with small changes;
    • A huge amount of traffic, especially on large pages;

    Option 2a - Almighty Server and Thin Answers


    You can try to fix the main drawback of the previous option. The server may not send the entire html component, but send only the "delta" - the changes that need to be made. Our answer then may become:

    {
      subscr_cnt: {
        html: "Подписчиков: 44",
        mode: "replace"
      },
      news: {
        html: "
  • Названы лучшие в мире сорта виски 2015 года
  • В Нью-Йорке появился детский сад для взрослых
  • ", mode: "append" } }

    Now the client determines the element that will change, and how it will change it, directly from the server’s response.

    Advantages of the approach:
    • No code duplication;


    Cons of the approach:
    • Still quite a lot of network traffic;
    • The client must send the server the current state of each component, encoded in some way, so that the server understands what to consider the delta;
    • The complexity of computing and recording deltas in case of nontrivial changes;
    • General complication of both client and server parts;

    Option 3 - omnipotent javascript


    You can shift all responsibility for generating html to the client. In this case, the server will only provide the data necessary for display. Answers, as in the first version, will contain only data:

    {
      subscr_cnt: 44,
      news:[
        {
          href: "/wiskey",
          name: "Названы лучшие в мире сорта виски 2015 года"
        },
        {
          href: "/kindergarden",
          name: "В Нью-Йорке появился детский сад для взрослых"
        }
      ]
    }
    

    So what is the essential difference from the first option? And it consists in the fact that the server does not perform the initial generation of the page, its assembly is already carried out by the client’s browser. This option only looks strange, it can come in handy if you need to reduce the load on the server.

    Advantages of the approach:
    • Low traffic volume - only necessary data is transmitted;
    • Reducing the load on the server;


    Cons of the approach:
    • High load on the user's computer;
    • Redundancy is possible - part of the client’s knowledge of the mapping may remain unclaimed if some events do not occur;


    Conclusion


    Each of the considered methods has the right to life, and can be used in projects of varying complexity. Personally, I most often saw the first option in the projects I met, despite violating my favorite DRY principle - Don`t repeat yourself.

    What principles do you use when developing dynamic pages?

    Also popular now: