简体   繁体   English

如何在没有xhr的情况下获取包含的js文件的内容?

[英]How to get an included js file's contents without xhr?

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://). local.js驻留在同一台服务器上,我知道通过执行xhr调用,我可以得到它的内容(如果不是在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. document.scripts集合对我没用。

Somewhat like getting innerHTML (which works for scripts defined in-page)? 有点像获取innerHTML(适用于页面中定义的脚本)?

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? 我不确定如何获取包含的javascript代码,也不知道为什么你需要这个,但是如何去另一个方向呢?

Instead of having a script tag, make a XHR call to the file and eval its contents + keep its contents as a variable also. 不要使用脚本标记,而是对文件进行XHR调用并评估其内容并将其内容保留为变量。

**Disclaimer: I cannot see why you would need this, nor would I actually suggest you use this method, but it's a work-around. **免责声明:我不明白为什么你会需要这个,我也不建议你使用这种方法,但这是一个解决方法。

Are you assuming XHR will not use the cached version? 您是否认为XHR不会使用缓存版本? It will, there may be a request, but it should be fast (reuse the same HTTP connection) and return 304 (not modified). 它可能会有一个请求,但它应该很快(重用相同的HTTP连接)并返回304(未修改)。 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). 因此,除非您的JavaScript文件的HTTP响应标头禁止或未指定缓存指令(但通常它们应该),否则将使用缓存版本。

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. 我怀疑虽然浏览器知道脚本的内容,但文档不知道它们,因此无法通过DOM API访问。 So you will have to use the XHR approach. 所以你必须使用XHR方法。 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. 运气好的话,如果你确保脚本被正确缓存,那么XHR请求无论如何都会从本地缓存中提取脚本内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM