Sean Robertson

Sean Robertson

1569918996

An Introduction to Service Workers in JavaScript

Service workers are a core part of Progressive Web Apps that allow caching of resources and web push notifications, among other things, to create an effective offline experience. They act as a proxy between web applications, the browser, and the network, allowing developers to intercept and cache network requests and take appropriate action based on the availability of the network.

A service worker runs on a separate thread, so it is non-blocking. This also means that it does not have access to DOM and other APIs available in the main JavaScript thread like cookies, XHR, web storage APIs (local storage and session storage), etc. Since they are designed to be fully asynchronous, they heavily use promises to wait for responses of network requests.

Due to security concerns, service workers only run over HTTPS and cannot be used in private browsing mode. However, you do not need a secure connection while making location requests (good enough for testing).

Browser Support

The service worker is a relatively new API that is only supported by modern web browsers. Therefore, we first need to check if the API is supported by the browser:

if('serviceWorker' in navigator) {
    // Supported 😍
} else {
    // Not supported 😥
}

Service Worker Registration

Before we start caching the resources or intercepting network requests, we must install a service worker in the browser. Since a service worker is essentially a JavaScript file, it can be registered by specifying the path of the file. The file must be accessible over the network and should only contain service worker code.

You should wait until the page is loaded, then pass the service worker file path to navigator.serviceWorker.register() method:

window.addEventListener('load', () => {
    if ('serviceWorker' in navigator) {
        // register service worker
        navigator.serviceWorker.register('/sw-worker.js').then(
            () => {
                console.log('SW registration succesful 😍');
            },
            err => {
                console.error('SW registration failed 😠', err)
            });
    } else {
        // Not supported 😥
    }
});

You can run the above code every time a page loads without any trouble; the browser will decide if the service worker is already installed or not and handle it accordingly.

Service Worker Lifecycle

The registration lifecycle consists of three steps:

  1. Download
  2. Install
  3. Activate

When a user first visits your website, the service worker file is immediately downloaded and installation is attempted. If the installation is successful, the service worker is activated. Any functionality that’s inside the service worker file is not made available until the user visits another page or refresh the current page.

Browser Events

Once the service worker is installed and activated, it can start intercepting network requests and caching resources. This can be done by listening to events emitted by the browser inside the service worker file. The browser emits the following events:

  • install is emitted when the service worker is being installed.
  • activate is sent when the service worker has been successfully registered and installed. This event can be used to remove outdated cache resources before installing a new version.
  • fetch is emitted whenever the web page requests a network resource. It can be anything: a new HTML document, an image, a JSON API, a stylesheet or JavaScript file, whatever that is available on a remote location.
  • push is sent by the Push API when a new push notification is received. You can use this event to display a notification to the user.
  • sync is invoked when the browser detects network availability after the connection was lost.

Serving Cached Resources

We can listen to install event when the service worker is installing to cache specific resources that would be need to serve the page when we are out of network:

const CACHE_NAME = 'site-name-cache';

self.addEventListener('install', event => {
    event.waitUntil(
        caches
            .open(CACHE_NAME)
            .then(cache =>
                cache.addAll([
                    'favicon.ico',
                    'projects.json',
                    'style.css',
                    'index.js',
                    'https://fonts.googleapis.com/css?family=Open+Sans:400,700'
                ])
            )
    );
});

The above example code uses the Cache API to store the resources in a cache named site-name-cache.

The self is a read-only global property that is used by the service workers to get access to themselves.

Now let us listen for a fetch event to check if the requested resource was already stored in the cache, and return it back if found:

// ...
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request).then(response => {
            if (response) {
                //found cached resource
                return response;
            }
            return fetch(event.request);
        })
    );
});

We look for a cache entry for the resource identified by the request property, and if not found, we make a fetch request to get it. If you want to cache new requests too, you can do it by handling the response of the fetch request and then adding it to the cache, like below:

//...
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request).then(response => {
            if (response) {
                //found cached resource
                return response;
            }

            // get resource and add it to cache
            return fetch(event.request)
                .then(response => {
                    // check if the response is valid
                    if (!response.ok) {
                        return response;
                    }

                    // clone the response
                    const newResponse = response.clone();

                    // add it to cache
                    caches.open(CACHE_NAME)
                        .then(cache =>
                            cache.put(event.request, newResponse)
                        );

                    // return response
                    return response;
                });
        })
    );
});

Service Worker Update

When the service worker is installed, it continues to run until it is removed by the user or updated. To update a service worker, all you need to do is upload a new version of the service worker file on the server. When the user visits your site, the browser will automatically detect the file changes (even just one byte is enough), and install the new version.

Just like the first time installation, the new service worker functionality will only be available when the user navigates to another page or refresh the current page.

On thing we can do is listen for activate event and remove the old cache resources. The following code does this by looping over all caches and deleting the cache that matches our cache name:

// ...
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(
                keys.map(cache => {
                    if (cache === CACHE_NAME) {
                        return caches.delete(cache);
                    }
                })
            );
        })
    );
});

That’s all for service workers introduction. If you want to learn more, check out ServiceWorker Cookbook — a collection of working, practical examples of using service workers in modern web sites.

#javascript #web-development #web-service

What is GEEK

Buddha Community

An Introduction to Service Workers in JavaScript

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company

Introduction With Basic JavaScript

The world’s most misunderstood programming language is JavaScript but JavaScript is now used by an incredible number of high-profile applications. So, it’s an important skill for any web or mobile developer to enrich the deeper knowledge in it.

Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world.

Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes. JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.

Let’s start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript’s types are:

· Number

· String

· Boolean

· Function

· Object

· Symbol

and undefined and null, which are … slightly odd. And Array, which is a special kind of object. Date and RegExp, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type of diagram looks like this:

#beginner-javascript #javascript #javascript-introduction #javascript-fundamental #basic-javascritp

Ajay Kapoor

1623988261

JS Development Company India | JavaScript Development Services

PixelCrayons’ JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Javascript Web Development Company

#javascript-web-development-services #javascript-development-company #javascript-development-companies #top-javascript-development-company #best-javascript-development-company

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers