Accessing <script src> Source Code

Currently, the source code of scripts with src can only be read by fetching them a second time. There should be a property of HTMLScriptElement which contains the source code.

1 Like

Isn’t it already there as the textContent of the element?

Obviously, the point is accessing the code of an external script embedded via the src attribute of the SCRIPT element that has empty textContent.

The same feature would be nice for any text-type external resources such as stylesheets, not just for scripts.

Could you add one or more use cases?

Also, is there a way to instruct the browser to serve the script from its network cache, when performing the fetch?

My use case is a testing framework. I want to watch for “error” and “unhandledrejection” events, and tie them back to the tests they originate in using the line and file. To do that I need the source of the test scripts, meaning I need to fetch the scripts again immediately after the page loads.

Couldn’t this force browsers to keep the JS source code in RAM where it can currently be freed, just in case the source is requested? That could bloat every web page.

Also there are already ways to get both source and script with only a single request - you could use fetch(..., { cache: "force-cache" }) or (IMO better) fetch the script as text (giving you the source), create a blob with the text, create a URL to the blob, then attach a script with the blob URL src.

1 Like

The use case certainly seems reasonable, but obscure enough that I suspect optimising for it is unlikely to get a lot of takeup…

It seems like browsers (at least Chrome) are already keeping the source files (in RAM? SSD?) while the page is open, accessible via Sources in Devtools. If they already have this easily available internally, it shouldnt be too hard to expose to sites.

Several browsers are regularly criticised for using too much memory, and have on-going engineering projects to reduce memory usage. This may well be one of the things in their sights. I think features that could have a per-page memory cost are not necessarily a good idea, especially when there are workarounds.

Perhaps have this via a property on the tag to opt in to the feature (or even a meta tag to opt all tags on the page in). By being opt in for quite a rare case it won’t prevent browsers optimising memory usage in future. Also as the main use case appears to be testing/development even sites that do use it will mostly remove the feature before hitting live so memory usage is even less of a concern.

If testing is the main use case for this, can’t a browser extension do this without requiring rendering engine changes?