search
HomeCMS TutorialWordPressGrowing 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

培养 Service Worker:不容错过的 5 个重要技巧

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:

培养 Service Worker:不容错过的 5 个重要技巧

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.

培养 Service Worker:不容错过的 5 个重要技巧

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.

培养 Service Worker:不容错过的 5 个重要技巧

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.

培养 Service Worker:不容错过的 5 个重要技巧

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.

培养 Service Worker:不容错过的 5 个重要技巧

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to add a comment box to WordPressHow to add a comment box to WordPressApr 20, 2025 pm 12:15 PM

Enable comments on your WordPress website to provide visitors with a platform to participate in discussions and share feedback. To do this, follow these steps: Enable Comments: In the dashboard, navigate to Settings > Discussions, and select the Allow Comments check box. Create a comment form: In the editor, click Add Block and search for the Comments block to add it to the content. Custom Comment Form: Customize comment blocks by setting titles, labels, placeholders, and button text. Save changes: Click Update to save the comment box and add it to the page or article.

How to copy sub-sites from wordpressHow to copy sub-sites from wordpressApr 20, 2025 pm 12:12 PM

How to copy WordPress subsites? Steps: Create a sub-site in the main site. Cloning the sub-site in the main site. Import the clone into the target location. Update the domain name (optional). Separate plugins and themes.

How to write a header of a wordpressHow to write a header of a wordpressApr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

How to display wordpress commentsHow to display wordpress commentsApr 20, 2025 pm 12:06 PM

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use <?php comments_template(); ?> tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to

How to upload source code for wordpressHow to upload source code for wordpressApr 20, 2025 pm 12:03 PM

You can install the FTP plug-in through WordPress, configure the FTP connection, and then upload the source code using the file manager. The steps include: installing the FTP plug-in, configuring the connection, browsing the upload location, uploading files, and checking that the upload is successful.

How to copy wordpress codeHow to copy wordpress codeApr 20, 2025 pm 12:00 PM

How to copy WordPress code? Copy from the admin interface: Log in to the WordPress website, navigate to the destination, select the code and press Ctrl C (Windows)/Command C (Mac) to copy the code. Copy from a file: Connect to the server using SSH or FTP, navigate to the theme or plug-in file, select the code and press Ctrl C (Windows)/Command C (Mac) to copy the code.

What to do if there is an error in wordpressWhat to do if there is an error in wordpressApr 20, 2025 am 11:57 AM

WordPress Error Resolution Guide: 500 Internal Server Error: Disable the plug-in or check the server error log. 404 Page not found: Check permalink and make sure the page link is correct. White Screen of Death: Increase the server PHP memory limit. Database connection error: Check the database server status and WordPress configuration. Other tips: enable debug mode, check error logs, and seek support. Prevent errors: regularly update WordPress, install only necessary plugins, regularly back up your website, and optimize website performance.

How to close comments with wordpressHow to close comments with wordpressApr 20, 2025 am 11:54 AM

How to turn off a comment in WordPress? Specific article or page: Uncheck Allow comments under Discussion in the editor. Whole website: Uncheck "Allow comments" in "Settings" -> "Discussion". Using plug-ins: Install plug-ins such as Disable Comments to disable comments. Edit the topic file: Remove the comment form by editing the comments.php file. Custom code: Use the add_filter() function to disable comments.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!