-->

How to include custom JS in AMP Page through SW?

2020-07-24 06:38发布

问题:

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

回答1:

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! :)



回答2:

@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.



回答3:

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