Tgwizman
Tgwizman

Reputation: 1538

Is it possible to get the text of a script that is loaded from a source as opposed to in line code?

Currently I'm just taking source of a script that is on the page.

The HTML:

<script type="text/plain">meow</script>

The JavaScript:

// returns "meow"
document.querySelector('script').text

I want to be able to load the script from another file.

The HTML:

<script type="text/plain" src="file.txt"></script>

file.txt:

meow

The JavaScript:

// returns "meow"
document.querySelector('script').textFromFile

Does anyone know if that's possible? I would assume it's not, and I haven't found anything on google that is what I'm asking.

Upvotes: 2

Views: 246

Answers (1)

Sampson
Sampson

Reputation: 268324

If the script has a src attribute you would need to fire of a request via XHR to that same path and pull in the text content of its response. Keep in mind this will require additional work if the script is being loaded from another domain. At that point you would need to make use of CORS, or introduce some other type of proxy to handle the cross-domain communication.

Upvotes: 1

Related Questions