How to include custom JS in AMP Page through SW?

孤者浪人 提交于 2019-12-04 15:01:38

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!