2

We have gone through from all possible blogs of AMP but couldn't find any way to include custom JS in AMP. This blog(https://www.ampproject.org/docs/guides/pwa-amp/amp-as-pwa#extend-your-amp-pages-via-service-worker) indicates that we can add Custom JS in AMP with the help of Service worker but haven't describe how to do it.

Please let us know How to do it.

Edit:- After adding JS at the run time, it again show the same old error, Please have a look to the image

enter image description here

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Anurag Bhakuni
  • 2,379
  • 26
  • 32

3 Answers3

2

Note in the mentioned blog post that you can extend your AMP pages

as soon as they’re served from the origin

Having a service worker in itself doesn't exempt you from AMP restrictions. However if you install a service worker in your AMP page, you can then begin to use AMP as a (progressive) web app, with less restrictions. There are multiple patterns you can use - this article covers the major patterns and this Google Codelab shows you how to implement them.

Hope that helps!

EDIT:

Yeah, okay I see what you mean. You could accomplish that by adding this code to the service worker:

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 src="extra.js" async ></script></body>');
          return new Response(body, init);
        });
      })
    );
  }
});

This will dynamically add the extra.js file to all the *amp.html pages that your app requests. I believe it will still validate, but I haven't tested it.

Note that this will only work when it's served from your origin (as opposed to the AMP Cache), because that's where your service worker has control.

This resource is where I found the code example (it has a soft paywall).

Let me know if it works! :)

David
  • 2,846
  • 3
  • 22
  • 34
  • Thanks David for the response, I need to know that if is there any way to add any script in AMP page through 'fetch'(addeventlistener) event in SW. – Anurag Bhakuni Feb 01 '18 at 09:39
  • @AnuragBhakuni okay I see what you mean, I've updated my answer for your specific question - does that work? – David Feb 01 '18 at 18:02
  • Thanks again @David, but it showing same error please have a look on edited part of my question. – Anurag Bhakuni Feb 02 '18 at 07:10
  • sorry @AnuragBhakuni! I forgot about your question. Check out this [demo I made](https://solar-reaction.glitch.me/) - if you refresh the page, you'll see the custom JS. The sample code is [here](https://glitch.com/edit/#!/solar-reaction?path=service-worker.js:22:0). Does that help you? – David Feb 20 '18 at 01:05
1

@DavidScales's answer is great if you want to specifically include your custom JS through a service worker for some reason. You could also just include your custom JS in a hidden amp-iframe on the page. Note that all of your custom js would have to be changed to reference the parent, so that it can access the AMP page's DOM.

See this thread.

Also see this thread for how to access the AMP page from inside the iframe.

Nick Searle
  • 157
  • 1
  • 7
0

The amp-install-serviceworker component enables service worker installation via same origin or via the Google AMP Cache.

Note : Service Workers are currently available in Chrome, Firefox and Opera.

How to use amp-install-serviceworker? CLICK HERE

Bachcha Singh
  • 3,850
  • 3
  • 24
  • 38