DEV Community

manish srivastava
manish srivastava

Posted on • Updated on

SERVER PUSH + SERVICE WORKER = FAST WEBSITE

Not so long ago, the capabilities of performance-oriented developers have changed markedly. And the advent of HTTP / 2 was perhaps the most significant change. HTTP / 2 is no longer a feature that we look forward to - it already exists (and successfully helps to cope with problems like blocking the beginning of the queue and uncompressed headers that exist in HTTP / 1), and Server Push comes with it !

This technology allows users to send site resources before they ask them. This is an elegant way to take advantage of the performance of HTTP / 1 optimization methods, such as embedding, and avoid the disadvantages associated with this practice.

Instead of waiting until the server arrives index.html, and then while the browser requests and receives styles.css, the user only needs to wait for an answer to his initial request. This answer will contain both files: and index.html, and styles.css. This means that the browser can start rendering the page faster than if it had to wait.

Alt text of image

As you can see, using Server Push can reduce page rendering time. And also - to solve some other problems, especially regarding front-end development.

yeah easy!!!

How to Use Server Push ?
1: Without Serviceworker.
2: With Serviceworker.

1: Without Serviceworker.

There are two ways to do this:

Web server settings (for example, httpd.confor .htaccessfor Apache);
a backend language function (for example, a PHP function header).

(A) IF YOU HAVE SERVER ACCESS:

.htaccess (Apache)

<FilesMatch "\.html$">
    Header add Link "</css/styles.css>; rel=preload; as=style"
    Header add Link "</js/scripts.js>; rel=preload; as=script"`<FilesMatch>

NGINX:
To enable preload, include the http2_push_preload directive in the configuration. https://www.nginx.com/blog/nginx-1-13-9-http2-server-push/

(B) IF YOU DO NOT HAVE SERVER ACCESS:

If your application is located on a shared hosting, where there is no way to change the server settings, then this method is what you need. You should be able to set this header in any server language. Just be sure to do this before you start sending the response body, in order to avoid possible runtime errors.

header("Link: </css/styles.css>; rel=preload; as=style");

What you see above is actually the tip of the resource preload( preload resource hint ). This is a separate optimization other than Server Push, but most (not all) HTTP / 2 implementations will push through the object specified in the header Link containing the resource hint preload. If the server or client refuses to accept the pushed resource, the client will still be able to initiate early retrieval of the specified resource.

HTTP/2 Server Push is awesome, but it isn’t a magic bullet.

It is fantastic for improving the load time of a web page when it first loads for a user, but it isn’t that great when they request the same web page again. The reason for this is that HTTP/2 Server Push is not cache “aware”. This means that the server isn’t aware about the state of your client. If you’ve visited a web page before, the server isn’t aware of this and will push the resource again anyway, regardless of whether or not you need it. HTTP/2 Server Push effectively tells the browser that it knows better and that the browser should receive the resources whether it needs them or not.

2: With Serviceworker.

Using Service Workers, you can easily cache assets on a user’s device. This means when a browser makes an HTTP request for an asset, the Service Worker is able to intercept the request and first check if the asset already exists in cache on the users device. If it does, then it can simply return and serve them directly from the device instead of ever hitting the server.

In order to start caching assets, I am going to use the Service Worker toolbox .

https://github.com/GoogleChromeLabs/sw-toolbox

It is a lightweight helper library to help you get started creating your own Service Workers. Using this library, we can actually cache the base web page with the path /push.

Add This Script to your HTML file:To register the Service worker (a js file)

  // Register the service worker
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./service-worker.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  }

Now ServerPush Service Worker: I’ve add the following code to the service-worker.js file.

(global => {
  'use strict';
  // Load the sw-toolbox library.
  importScripts('/js/sw-toolbox/sw-toolbox.js');
 // The route for any requests
  toolbox.router.get('/push', global.toolbox.fastest);
  toolbox.router.get('/images/(.*)', global.toolbox.fastest);
  toolbox.router.get('/js/(.*)', global.toolbox.fastest);
  // Ensure that our service worker takes control of the page as soon as possible.
  global.addEventListener('install', event => event.waitUntil(global.skipWaiting()));
  global.addEventListener('activate', event => event.waitUntil(global.clients.claim()));
})(self);

The best thing about the code above is that if any of the assets exist in cache, we will instantly return the cached version instead of waiting for it to download. If the asset doesn’t exist in cache, the code above will add it into cache so that we can retrieve it when it’s needed again.

The next time a user visits the page, the Service Worker will intercept the request and serve the asset directly from cache. Amazing!

I hope you people like the above article and learned something.

You are most welcome to join my team form for joining .

Contact email: Manishfoodtechs@gmail.com.

If you have any problem, our team is also engaged in professional consultancy and delivery.

Also you are most welcome to join OPEN SOURCE INTELLIGENT SYSTEM (OSINT)if you can help in open source project regarding safeguarding humans from various diseases like CORONA outbreak
https://github.com/Manishfoodtechs/OSINTHRH/wiki

Don't forget to Follow, like or tag me :).

Top comments (3)

Collapse
 
leob profile image
leob

This is great, I am going to look at this for my new project.

Collapse
 
thebouv profile image
Anthony Bouvier

You might want to consider redoing your code blocks using code and syntax highlight in Markdown:

github.com/adam-p/markdown-here/wi...

Collapse
 
manishfoodtechs profile image
manish srivastava
Thanks Anthony.  DID    :)