Mojolicious::Plugin::ServiceWorker - plugin to add a Service Worker
# Mojolicious::Lite
plugin 'ServiceWorker' => {
route_sw => '/sw2.js',
precache_urls => [
],
};
app->serviceworker->add_event_listener(push => <<'EOF');
function(event) {
if (event.data) {
console.log('This push event has data: ', event.data.text());
} else {
console.log('This push event has no data.');
}
}
EOF
Mojolicious::Plugin::ServiceWorker is a Mojolicious plugin.
Mojolicious::Plugin::ServiceWorker inherits all methods from Mojolicious::Plugin and implements the following new ones.
my $p = $plugin->register(Mojolicious->new, \%conf);
Register plugin in Mojolicious application, returning the plugin object. Takes a hash-ref as configuration, see "OPTIONS" for keys.
The service worker route. Defaults to /serviceworker.js
. Note that
you need this to be in your app's top level, since the service worker
can only affect URLs at or below its "scope".
If a true value, console.log
will be used to indicate various events
including SW caching choices.
An array-ref of URLs that are relative to the SW's scope to load into the SW's cache on installation. The SW URL will always be added to this.
An array-ref of URLs. Any fetched URL in this list will never be cached, and always fetched over the network.
As above, except the matching URL will never be re-checked. Use only where you cache-bust by including a hash in the filename.
As above, except the matching URL will be fetched from the network every time and used if possible. The cached value will only be used if that fails.
Any URL not matching these three criteria will be treated with a "cache first" strategy, also known as "stale while revalidate": the cached version will immediately by returned to the web client for performance, but also fetched over the network and re-cached for freshness.
my $route_name = $c->serviceworker->route;
The configured "route_sw" route.
my $config = $c->serviceworker->config;
The SW configuration (a hash-ref). Keys: debug
, precache_urls
,
network_only
, cache_only
, network_first
.
my $config = $c->serviceworker->add_event_listener(push => <<'EOF');
function(event) {
if (event.data) {
console.log('This push event has data: ', event.data.text());
} else {
console.log('This push event has no data.');
}
}
EOF
Add to the service worker an event listener. Arguments are the event name, and a JavaScript function expression that takes the correct args for that event.
my $listeners = $c->serviceworker->event_listeners;
Returns a hash-ref mapping event name to array-ref of function
expressions as above. install
and fetch
are provided by default.
Various templates are available for including in the app's templates:
A snippet of JavaScript that will install the supplied service
worker. Include it within a script
element:
<script>
%= include 'serviceworker-install'
</script>