Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Developers can build more resilient and user-friendly web applications that perform reliably under various network conditions. Also, it is possible to warm cache a selection of resources. This is powerfull as it allows applications to partially work offline.
The default strategy applied for resources is Network First i.e. the resource from the web server is fetched first. In case of failure, the cached data is served. By default, the service worker will wait 3 seconds before serving the cached version. This value can be configured.
Please note that you can refer to any URLs, but only URLs served by your application will be cached.
The match_callback
option is designed to specify the condition used to determine which requests should be cached based on the request URL. This option can take different types of values, such as
A regular expression
A Javasrcipt callback
A prefixed statement
You can directly pass a regular expression as a string or using the JS RegExp
object.
match_callback: '"/styles/.*\.css"'
match_callback: 'new RegExp("/styles/.*\.css")'
Quotes are important!
Workbox gives you the url
, the params
, the request
and the event
objects. You can use any of those parameters to match with your cache.
match_callback: '({url}) => url.pathname === "/special/url"'
match_callback: '({request}) => request.destination === "image"'
Quotes are important!
This bundle allows the use of handlers to avoid the use of JS and simplify the way you declare the callbacks.
For instance, using startsWith: /pages/
as the match_callback
value means that any request URL that begins with /pages/
will be considered a match and thus eligible for caching under the defined cache_name
.
Or destination: image
is identical to match_callback: '({request}) => request.destination === "image"'
.
This approach empowers developers to optimize their web application's performance by strategically caching resources based on URL patterns, ensuring that users enjoy faster load times and a smoother overall experience, even in offline scenarios or under suboptimal network conditions.
Provided Match Callback Handlers:
If needed, you can create your own Match Callback Handler. It must implement SpomkyLabs\PwaBundle\MatchCallbackHandler\MatchCallbackHandler
and should return a value compatible with the capture
argument of the Workbox method registerRoute
.
In the following example, setting match_callback: my-videos
is a simplified way to match only videos served from a specific origin.
The class shall be declared as a service.
The cache_name
parameter is used to customize the cache name. If not set, a default value is defined.
The strategy
option corresponds to the Workbox strategy.
CacheFirst (Cache Falling Back to Network)
This strategy serves responses from the cache first, falling back to the network if the requested resource is not in the cache. It is ideal for assets that do not update frequently.
NetworkFirst (Network Falling Back to Cache)
The reverse of Cache First, this strategy tries to fetch the response from the network first. If the request fails (e.g., due to being offline), it falls back to the cache. Suitable for content where freshness is more critical.
StaleWhileRevalidate
This strategy serves cached responses immediately while silently fetching an updated version from the network in the background for future use. It is a good compromise for resources that need to be updated occasionally without compromising the user experience with loading delays.
NetworkOnly
A strategy that only uses the network, not attempting to cache or match responses from the cache. This is useful for non-cachable responses such as API requests returning user-specific data.
CacheOnly
Conversely, the Cache Only strategy serves responses from the cache, ignoring the network. This is ideal for offline applications where you want to ensure that only cached resources are served.
Leveraging Workbox strategies allows you to fine-tune how your application handles caching, ensuring that your users get the best possible experience whether they are online or offline.
The Workbox network_timeout
option indicates the number of seconds before the request falls back to the strategy. It is only available with NetworkFirst and NetworkOnly.
When set, this indicates the expiration strategy used for the resource cache. max_age can be in seconds or a human-readable string
max_age: 3600
and max_age: 1 hour
are similar.
max_entries
is a positive number. When the cache reaches the number of cached resources, old resources are removed.
When making a request, a range
header can be set that tells the server to return only a portion of the full request. This is useful for certain files like a video file, where a user might change where to play the video.
By setting the range_requests: true
, this type of requests will be supported.
When accessing a page with the StaleWhileRevalidate
strategy, the Service Worker will verify if a page update exists and will save it in the cache if any.
The broadcast parameter will tell the Service Worker to send a broadcast message in case of an update. This is usefull to warn the user it is reading an outdated version of the page and ask for a page reload.
In the example below, the message
is catched and, if it is of type "workbox-broadcast-update
" and the URL matches with the current URL, a toast notification is displayed for 5 seconds.
By default, the page header used to check if the page is outdated or not are Content-Length
, ETag
, Last-Modified
. These headers can be changed.
By default, all responses with a 0
or 200
status code and that match with the match_callback
option will be cached. It is possible to tell Workbox to cache only resources with a dedicated header or other status codes:
Pattern | Description | Example |
---|---|---|
navigate
Matches all resources the user navigates to.
No example. This is an exact match
destination:
Matches a certain type of resource. Available values are listed on the Request object documentation.
destination: audio
destination: style
destination: video
route:
Matches the exact Symfony route. Shall not have required parameters
route: app_homepage
route: app_princing
pathname:
Matches an exact pathname
pathname: /foo/bar.docx
pathname: /report.pdf
origin:
Matches all requests to the origin
origin: example.com
origin: google.com
startsWith:
Matches all pathnames starting with the value
startsWith: /dashboard
startsWith: /admin
endsWith:
Matches all pathnames ending with the value
endsWith: .css
endsWith: -report.pdf
By default, a maximum of 60 images are cached for 1 year. The supported image extensions extensions are as follows:
This can be changed using the next configuration options
This cache is different from the Asset one as it corresponds to images that are not managed by Asset Mapper
By default, 30 fonts can be cached for 1 year. This only comprises fonts served directly by your application. The supported fonts are as follows:
This can be changed using the next configuration options:
Fonts served by Google Fonts have a dedicated rule. It is enabled by default and you can disable it or customize some parameters.
The Site Manifest file can be cache by the bundle. This feature is enabled by default and mainly used to avoid error messages in the console and adds no significant benefits over the time.
Workbox makes it easy to create robust offline experiences in web applications. When a user navigates to a page without an internet connection, instead of showing an error, your application can serve a predefined fallback page, image or font.
page_fallback
can be a relative URL, a route name or a route name with parameters. See URL parameter for more information.
image_fallback
and font_fallback
refer to assets delivered by Asset Mapper or an URL to the font file.
Contains a breaking change compared to v1.0.x
The cache is populated with all assets managed by Asset Mapper. By default, it includes all types of well recognized assets such as images, stylesheets or scripts:
This can be changed using the next configuration options:
This bundle provides a simple Workbox integration path. Service Workers are not that easy to write. It can become a nightmare when dealing with mutliple caching rules or offline capabilities.
Workbox takes the pain out of service worker creation by providing a set of tools and best practices that can be used out of the box. It’s like having an expert by your side, guiding you through the complexities of browser caching and service worker logic.
This bundle builds on top of Workbox and includes several options so you don't need to write a line of Javascript to have a fully functional Service Worker.
Workbox provides various caching strategies to make it easy to manage how requests are handled by the service worker. One of the features is the ability to maintain a page cache for certain URLs or routes.
A warm cache refers to pre-loading URLs during the service worker installation phase. This ensures that those URLs are cached and readily available even before they are requested by the user.
The URLs to be pre-loaded are likely the pages that users will definitely navigate to. For example, the main functionality of your application, the pricing page or a page with the latest news that users will definitely read.
When the service worker is installed, Workbox will automatically cache the resources specified in the list. These files will remain cached and will be instantly available to the user, contributing to a swift user experience.
Hereafter the main benefits of Precache:
Faster Load Times: Since assets are stored locally, web applications can load faster, providing a better user experience.
Offline Support: Precached assets ensure that the application is usable even without a network connection.
Consistency: All users receive the same version of files, ensuring a consistent experience.
Background Updates: Assets are updated in the background, preventing any interruption to the user experience.
Precaching: Workbox can precache the assets in your web app and keep them up to date.
Runtime Caching: Flexible strategies for handling runtime requests, such as stale-while-revalidate, cache first, and network first.
Request Routing: Easily define how different types of requests are handled by your service worker.
Background Sync: Integrate background sync to replay failed requests once connectivity is restored.
Offline Fallback: allow your service worker to serve a web page, image, or font if there's a routing error for any of the three, for instance if a user is offline and there isn't a cache hit.
Workbox is enabled by default. You can disable it completely if you do not need it.
When the service worker changes and is activated, the cache is purged. This feature is made to avoid the cache to grow in size and prevent your application to reach the limit of the host system or browser.
You can disable the cache purge, however you have to make sure the cached data is managed by other means.
TO BE WRITTEN
Background Sync is a feature provided by service workers that enables your Progressive Web App to defer actions until the user has stable connectivity. This is particularly useful for ensuring any requests or data submitted by the user are not lost if their internet connection is unreliable.
queue_name
: Unique queue name for each queue to easily identify and manage separate background sync processes. This is essential for categorizing different types of requests such as API calls and form submissions.
match_callback
: .
method
: Specifies the HTTP method (e.g., POST) for the requests to be queued. This helps in filtering which request methods should be considered for background synchronization.
max_retention_time
: The maximum time (in minutes) that a request will be retried in the background. This is crucial for managing storage and ensuring outdated requests are not unnecessarily retried.
force_sync_fallback
: (Optional) A boolean value that, when set to true, forces the background sync to attempt a sync even under conditions where it might not normally do so. Useful in critical data submission scenarios.
broadcast_channel
: Specifies the name of the Broadcast Channel API channel used to communicate the status of the background sync process to the rest of the application. This enables real-time update capabilities on the user interface regarding the sync status. See for communication between the Service Worker and the frontend.
By default, the bundle uses Workbox 7.0.0
which was released end of May 2023. The files are provided by the bundle so that all files are served by your server.
If needed, you can use a CDN and a different version.