Injecting JavaScript with a service worker

As well as just caching pages and assets for offline use, we can add things that AMP doesn't normally permit, such as custom JavaScript. The following is a very basic example of how we could inject custom JavaScript into an AMP page with the service worker. We modify the service worker fetch block to include the extra.js file in any URL path that matches *amp.html:

self.addEventListener('fetch', e => {  var url = new URL(e.request.url);  if(url.pathname.split('/').pop().endsWith('amp.html')) {    e.respondWith(      fetch(e.request).then(response => {        var init = {          status:     200,          statusText: "OK",          headers: {'Content-Type': 'text/html'}        };        return response.text().then(body => {          body = body.replace('</body>', '<script ...

Get AMP: Building Accelerated Mobile Pages now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.