问题描述
我们遍历了AMP的所有可能博客,但找不到在AMP中包含自定义JS的任何方法.此博客( https://www.ampproject.org/docs/guides/pwa-amp/amp-as-pwa#extend-your-amp-pages-via-service-worker )表示我们可以添加在Service worker的帮助下,AMP中的自定义JS尚未说明如何实现.
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.
请让我们知道如何做.
-在运行时添加JS之后,它再次显示相同的旧错误,请查看图片
- After adding JS at the run time, it again show the same old error, Please have a look to the image
推荐答案
在上述博客文章中,请注意您可以扩展AMP页面
Note in the mentioned blog post that you can extend your AMP pages
拥有服务人员本身并不能免除AMP限制.但是,如果您在AMP页面中安装了Service Worker,则可以以较少的限制开始将AMP用作(渐进式)Web应用程序.您可以使用多种模式-本文涵盖了主要模式模式和此Google Codelab 向您展示了如何实现它们.
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.
希望有帮助!
是的,好的,我明白你的意思了.您可以通过将以下代码添加到服务工作者中来实现这一点:
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);
});
})
);
}
});
这会将extra.js
文件动态添加到您的应用程序请求的所有*amp.html
页中.我相信它仍然可以验证,但我尚未对其进行测试.
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.
请注意,这仅在从您的来源(而不是AMP缓存)提供服务时起作用,因为这是服务工作者可以控制的地方.
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! :)
这篇关于如何通过SW在AMP Page中包含自定义JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!