如何在没有 xhr 的情况下获取包含的 js 文件的内容?
这可能吗?
<html>
<script src="local.js>
<script>
// get contents of local.js file here without doing an ajax call?
</script>
</html>
local.js 驻留在同一服务器上,我知道通过执行 xhr 调用我可以获取其内容(如果不在 file:// 上)。
但是,由于浏览器已经同步请求它,因此文档知道它的内容,所以我希望有一种方法可以访问它? document.scripts 集合对我没有帮助。
有点像获取innerHTML(适用于页面内定义的脚本)?
is this possible?
<html>
<script src="local.js>
<script>
// get contents of local.js file here without doing an ajax call?
</script>
</html>
local.js resides on the same server, and I know that by doing an xhr call I can get its contents (if not on file://).
But, as it is already requested synchronously by the browser, its contents is known to the document so I hope there is a way to access it? The document.scripts collection was no help to me.
Somewhat like getting innerHTML (which works for scripts defined in-page)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定如何获取包含的 javascript 代码,也不知道为什么需要这个,但是换个方向怎么样?
不要使用脚本标签,而是对文件进行 XHR 调用并评估其内容 + 也将其内容保留为变量。
**免责声明:我不明白你为什么需要这个,我实际上也不建议你使用这个方法,但这是一个解决方法。
I'm not sure on how to get the included javascript code, nor why you would need this, but how about going the other direction?
Instead of having a script tag, make a XHR call to the file and eval its contents + keep its contents as a variable also.
**Disclaimer: I cannot see why you would need this, nor would I actually suggest you use this method, but it's a work-around.
您是否假设 XHR 不会使用缓存版本?会的,可能会有一个请求,但它应该很快(重用相同的 HTTP 连接)并返回 304(未修改)。因此,除非您的 JavaScript 文件的 HTTP 响应标头禁止或不指定缓存指令(但通常应该这样做),否则将使用缓存版本。
Are you assuming XHR will not use the cached version? It will, there may be a request, but it should be fast (reuse the same HTTP connection) and return 304 (not modified). So the cached version will be used unless your JavaScript file's HTTP response headers prohibit or do not specify caching directives (but usually they should).
我怀疑虽然浏览器知道脚本的内容,但文档不知道它们,因此无法通过 DOM API 访问。所以你必须使用 XHR 方法。幸运的是,如果您确保脚本被正确缓存,XHR 请求无论如何都会从本地缓存中提取脚本内容。
I suspect that while the contents of the script are known to the browser, they're not known to the document, and are therefore not accessible via the DOM API. So you will have to use the XHR approach. With a bit of luck, if you ensure the script is properly cached, the XHR request will pull the script contents from the local cache anyway.