How to get js file contents without xhr?

Is it possible?

<html> <script src="local.js> <script> // get contents of local.js file here without doing an ajax call? </script> </html> 

local.js is on the same server, and I know that by making an xhr call, I can get its contents (if not in the file: //).

But, since it is already requested synchronously by the browser, its contents are known to the document, so I hope there is a way to access it? The collection of document.scripts did not help me.

Sounds like getting innerHTML (which works for scripts defined on the page)?

+6
source share
3 answers

I'm not sure how to get the javascript code included, and why you need it, but what about going in a different direction?

Instead of having a script tag, make an XHR call to the file and check its contents + save its contents as a variable.

** Disclaimer: I do not understand why you need it, and I would not suggest you use this method, but this is a workaround.

+1
source

Do you assume that XHR will not use the cached version? This may be a request, but it must be fast (reuse of the same HTTP connection) and return 304 (not changed). Thus, the cached version will be used if your HTTP headers of the HTTP JavaScript files prohibit or do not specify caching directives (but usually they should).

+1
source

I suspect that although the contents of the script are known to the browser, they are not known to the document and therefore are not accessible through the DOM API. So you have to use the XHR approach. If you're lucky, if you make sure the script is cached correctly, the XHR request will pull the contents of the script from the local cache.

-1
source

Source: https://habr.com/ru/post/891088/


All Articles