Reputation: 259
I want to read the js source code of a script loaded via a src attribute with pure javascript.
Like from a html script tag:
<script id=myFile type="text/javascript" src="file.js"></script>
var code = document.getElementById('myFile').textContent
But the above doesn't work.
This works however :
<script id=myFile>
console.log("This works");
</script>
var code = document.getElementById('myFile').textContent
Now, code contains "console.log("This works");"
Does somebody know how i can archive this with a js file loaded, instead of writing the js code in the html file?
Upvotes: 4
Views: 1442
Reputation: 1137
Event though that you can attach a load
listener to a <scritp async src="..."></>
, there's no way to access the plain text of the loaded object.
You will need to fetch your script manually and reading the content of it. You can do that with the following:
fetch('path/to/script')
.then(res => {
return res.text();
})
.then(text => {
console.log(text);
});
Upvotes: 1
Reputation: 943108
There is no API to read the source code of a script loaded via a src
attribute. The only way to access it is to make another HTTP request to that URL (e.g. with fetch
or XMLHttpRequest
).
Upvotes: 1