Growing Service Workers: 5 Important Tips You Can't Miss
The browser's Service Worker API allows web designers to offer visitors something they never had before: access to a website or web application even when they are offline, whether for a short or long period of time.
p>
Whether you want to make sure your visitors can still read your website while walking through a train tunnel, or you want to create an app that doesn't require an internet connection, Service Workers has the perfect solution.
As great as Service Workers are, there are some obstacles that may slow down your progress when you first start coding them - unless you realize in advance what those obstacles are. This tutorial will provide you with five basic tips for service worker development, which we hope will help you avoid these problems and save you from the associated troubleshooting headaches.
before the start
If you’re new to Service Workers, check out our beginner’s course Simple Service Workers for Offline Websites and Jeremy Keith’s book Going Offline, both available on Envato Elements.
1. Place your Service Worker script into the root directory
The earliest problems you may encounter when writing your first service
worker, you could probably do what you've always done and put your script
Go into a subdirectory named js
or scripts
. However, for service personnel, this mundane operation can cause problems.
The reason is that, by default, the scope of a Service Worker is defined by its location. what does that mean? This means that if you place a script in the /js
directory, its scope is now limited to that /js
directory. Therefore, it can only handle page requests from www.yoursite.com/js/
and completely ignore other requests, such as those from www e.g. .yoursite.com
or www.yoursite.com/news/
.
This limited scope in turn means that you won't be able to provide offline fallback for large parts of your site. In order for your service worker to handle any request from any part of your site, its scope must be all-inclusive.
Note: You can actually override the default scope of a Service Worker when registering, e.g.
navigator.serviceWorker.register('/sw.js', { scope: '/' });
With this approach, you can still have all your scripts in a subdirectory if doing so is important to your project.
But generally speaking, the easiest way is to put your Service Worker in the root directory, thus automatically setting its scope to cover the entire site.
2. Using the Application Panel in Chrome / Chromium Development Tools
While all major browsers support Service Workers, currently Chrome or Chromium is arguably the best browser for developing them. This is thanks to the very useful application panel in the developer tools. As you go through the development process, you will virtually live in this tab:
In this tab there is a dedicated section for service workers where you can verify that your script is registered, active, and running. You can also use this tab to simulate an offline state, temporarily bypassing service workers, and manually unregistering previous scripts that are no longer needed.
3.Don’t use hard reloading
In addition to not placing scripts in subdirectories, another development habit that must be broken when composing Service Workers is using "hard reload" or "clear cache and hard reload". You've probably done this thousands of times while testing your site, use this feature to clear your cache and make sure you see an accurate reflection of your development changes. But with a Service Worker, this doesn't have the desired effect.
when You have a registered and active service person, any user using "hard Reload" will bypass it completely. You may hard reload your site, see Your code doesn't execute the way you expect and think you've made a mistake, only to later realize the script never ran the first time Place.
So the bad news is that "hard reload" and "clear cache and hard reload" are out of scope during Service Worker development, which brings us to the next question:
how Can you refresh the page correctly and test your Service Worker code? Does it change if you can't use "hard reload" or "clear cache and hard reload"?The answer to this question lies in the following two techniques:
4.Check the "Update on reload" box
By default, when you refresh the page that the Service Worker is being tested on, you won't actually see the results of any code changes. This is because the version of the script you originally registered remains active in the browser, even after the page reloads, unless you take explicit action to update it.
So again we have a situation where you may be refreshing your page and wondering why your code changes didn't take effect unless You know the quirks of your service staff.
To ensure that the latest version of the script is always loaded, go to the Application tab and check the Update on Reload box. This ensures that every time the page is reloaded (remember, only use normal reloads, not hard reloads), the browser automatically updates the Service Worker for you.
NOTE: There is an additional option to click the Update link that appears next to the registered Service Worker, but it is usually easier to use the auto-reload method.
5.Check and manually delete cache objects
Applications We’re Going to Touch The last very handy feature of the tab is the ability to view the objects stored in the cache and delete them manually if necessary. Given that we don't want to use clearing caches and hard reloading, this feature will be an important part of the Service Worker development process.
In the left column of the Applications tab you will see an area Marked Cache Storage. If you expand this area you will be able to see Any cache objects held in storage related to the current URL.
Click on any item and you can check it content, which is very helpful for verifying the resource you want Offline services are being added to the cache correctly by your service workers.
To delete cached objects that are no longer needed, simply right-click on the object and select Delete.
Between this cache object deletion feature and the Update on reload checkbox, you can set it up to stick with normal page reloads while Still make sure you test the latest changes to your work properly.
Summarize
- Generally speaking, place the service worker script in the root directory of the project so that the entire website is within its scope.
- Use Chrome/Chromium's "Applications" tab when developing.
- Do not use hard reload or clear cache and hard reload .
- Check the Update on reload box in the Application tag to ensure that the registered Service Worker is up to date.
- If necessary, delete cache objects manually via the Cache Storage section of the Application tab, where you can also inspect the cache object contents.
For more information about Service Workers, check out our new course Simple Service Workers for Offline Websites and Jeremy Keith’s book Going Offline (now available on Envato Elements).
The above is the detailed content of Growing Service Workers: 5 Important Tips You Can't Miss. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.
