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