如何在 Service Worker 中动态加载 Javascript 文件? [英] How to load Javascript file in a Service Worker dynamically?
问题描述
我不能使用任何涉及动态创建 标签的解决方案,因为
document
不存在于 ServiceWorker 上下文中.
I can't use any solutions that involve creating a <script>
tag dynamically because document
does not exist in a ServiceWorker context.
在这种情况下,我想加载分析工具包,以便我可以跟踪用户何时与软件触发的通知进行交互.
In this case I want to load analytics toolkit so I can track when SW-triggered Notifications are interacted with by the user.
有什么想法吗?
推荐答案
这听起来像是 importScripts()
方法.
That sounds like the intended use case of the importScripts()
method.
导入的脚本与您的服务工作者共享全局范围,因此通过例如 self.addEventListener()
或 self.someIdentifier = ' 修改
的效果与在主 Service Worker 脚本中的效果相同.self
blah'
The imported script shares the global scope with your service worker, so modifying self
via, e.g., self.addEventListener()
or self.someIdentifier = 'blah'
will have the same effect as it would from within the main service worker script.
这篇关于如何在 Service Worker 中动态加载 Javascript 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!