tag? If I have a script tag like this:

How can I get the contents of a file indicated as "src" of the <script> tag?

If I have a script tag like this:

<script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"> </script> 

I would like to get the contents of the script.js "file. I am thinking of something like document.getElementById("myscript").text , but in this case it does not work.

+53
javascript
Sep 29 '08 at 12:15
source share
15 answers

Do you want to get the contents of the file http://www.example.com/script.js ? If so, you can refer to AJAX methods to extract its contents, assuming it is on the same server as the page itself.

Could you talk about what you are trying to achieve?

+10
Sep 29 '08 at 12:20
source share

I know this a bit late, but some browsers support the LINK property rel="import" .

http://www.html5rocks.com/en/tutorials/webcomponents/imports/

 <link rel="import" href="/path/to/imports/stuff.html"> 

Otherwise, ajax is still preferred.

+8
Mar 01 '16 at 19:12
source share

I do not think that the content will be accessible through the DOM. You can get the value of the src attribute and use AJAX to request a file from the server.

+6
Sep 29 '08 at 12:25
source share

if you want the contents of the src attribute, you will need to execute an ajax request and look at the feedback. If you have js in between and you can access it through innerHTML.

This may be of interest: http://ejohn.org/blog/degrading-script-tags/

+1
Sep 29 '08 at 12:21
source share

I had the same problem. There seems to be no way (except ajax) to solve this problem in html files. But when I am in php, at least the following turned out to be very useful:

 <script type="text/javascript" id="myScript"><?php readfile('filepath/myScript.js'); ?></script> 

You can then capture the contents of the script tag with the usual getElementById('myScript').text;

+1
Aug 27 '14 at 23:53 on
source share

.text made you the contents of the tag, you just have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file, you will follow the link and make an ajax request for it.

0
Sep 29 '08 at 12:23
source share

In a comment on my previous answer:

I want to save the contents of the script so that I can cache it and use it directly after a while without having to retrieve it from an external web server (not on the same server as on the page)

In this case, you better use the server side of the script to extract and cache the script file. Depending on the serverโ€™s settings, you can simply upload the file (periodically via cron if you expect it to change) or do something similar with a small script in your language of your choice.

0
Sep 29 '08 at 12:27
source share

You want to use the innerHTML property to get the contents of the script tag:

 document.getElementById("myscript").innerHTML 

But as @olle said in another answer, you probably want to read: http://ejohn.org/blog/degrading-script-tags/

0
Sep 30 '08 at 0:14
source share

yes, Ajax is a way to do this, as in the accepted answer. If you go into the details, there are many pitfalls. If you use jQuery.load(...) , the wrong content type is assumed (html instead of application / javascript), which can ruin things by putting unwanted <br> in your (scriptNode) .innerText and the like. Then, if you use jQuery.getScript(...) , the loadable script is executed immediately, which may not be what you want (it may ruin the order in which you want to load the files if you have several of them.)

I found it better to use jQuery.ajax with dataType: "text"

I used this Ajax technique in a frameset project, where a set of frames and / or multiple frames needs the same JavaScript to avoid the server re-sending this JavaScript several times.

Here is the code, tested and works:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html> <head> <script id="scriptData"> var scriptData = [ { name: "foo" , url: "path/to/foo" }, { name: "bar" , url: "path/to/bar" } ]; </script> <script id="scriptLoader"> var LOADER = { loadedCount: 0, toBeLoadedCount: 0, load_jQuery: function (){ var jqNode = document.createElement("script"); jqNode.setAttribute("src", "/path/to/jquery"); jqNode.setAttribute("onload", "LOADER.loadScripts();"); jqNode.setAttribute("id", "jquery"); document.head.appendChild(jqNode); }, loadScripts: function (){ var scriptDataLookup = this.scriptDataLookup = {}; var scriptNodes = this.scriptNodes = {}; var scriptNodesArr = this.scriptNodesArr = []; for (var j=0; j<scriptData.length; j++){ var theEntry = scriptData[j]; scriptDataLookup[theEntry.name] = theEntry; } //console.log(JSON.stringify(scriptDataLookup, null, 4)); for (var i=0; i<scriptData.length; i++){ var entry = scriptData[i]; var name = entry.name; var theURL = entry.url; this.toBeLoadedCount++; var node = document.createElement("script"); node.setAttribute("id", name); scriptNodes[name] = node; scriptNodesArr.push(node); jQuery.ajax({ method : "GET", url : theURL, dataType : "text" }).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node)); } }, makeFailHandler: function(name, node){ var THIS = this; return function(xhr, errorName, errorMessage){ console.log(name, "FAIL"); console.log(xhr); console.log(errorName); console.log(errorMessage); debugger; } }, makeHandler: function(name, node){ var THIS = this; return function (fileContents, status, xhr){ THIS.loadedCount++; //console.log("loaded", name, "content length", fileContents.length, "status", status); //console.log("loaded:", THIS.loadedCount, "/", THIS.toBeLoadedCount); THIS.scriptDataLookup[name].fileContents = fileContents; if (THIS.loadedCount >= THIS.toBeLoadedCount){ THIS.allScriptsLoaded(); } } }, allScriptsLoaded: function(){ for (var i=0; i<this.scriptNodesArr.length; i++){ var scriptNode = this.scriptNodesArr[i]; var name = scriptNode.id; var data = this.scriptDataLookup[name]; var fileContents = data.fileContents; var textNode = document.createTextNode(fileContents); scriptNode.appendChild(textNode); document.head.appendChild(scriptNode); // execution is here //console.log(scriptNode); } // call code to make the frames here } }; </script> </head> <frameset rows="200pixels,*" onload="LOADER.load_jQuery();"> <frame src="about:blank"></frame> <frame src="about:blank"></frame> </frameset> </html> 

related question

0
Feb 27 '17 at 2:04 on
source share

If you want to access the attributes of the <script> , not the contents of script.js, then XPath may well be what you need.

This will allow you to get each of the script attributes.

If this is the contents of an example.js file, then you can run an AJAX request to receive it.

-one
Sep 29 '08 at 12:22
source share

If the src attribute is provided, user agents should ignore the contents of the element , if you need to access it from an external script, then you are probably doing something wrong.

Update. I see you added a comment saying that you want to cache the script and use it later. For what purpose? Assuming your HTTP is caching , your caching needs are likely to be taken care of by the browser.

-one
Sep 29 '08 at 12:23
source share

I would suggest that the answer to this question uses the "innerHTML" property of the DOM element. Of course, if the script is loaded, you do not need to make an Ajax call to receive it.

So Sugendran should be right (I donโ€™t know why he was voted without explanation).

 var scriptContent = document.getElementById("myscript").innerHTML; 

The innerHTML property of the script element should provide you the contents of the scripts as a string if the script element:

  • inline script or
  • which the script loaded (if the src attribute is used)

olle also gives an answer, but I think he was "confused" in that he suggested that he needs to be downloaded via ajax first, and I think he meant "inline" instead of in between.

if you have js in between and you can access it through innerHTML.




Regarding the usefulness of this method:

I tried to use this method to register errors on the client side (from javascript exceptions) after receiving "undefined variables" that are not contained in my own scripts (for example, incorrectly written scripts from toolbars or extensions) - so I donโ€™t think it such an exit idea.

-one
Feb 07 '11 at 22:30
source share

Using a 2008 style DOM binding is likely to be:

 document.getElementById('myscript').getAttribute("src"); document.getElementById('myscript').getAttribute("type"); 
-2
Sep 29 '08 at 13:39
source share

Hope you are already using the JavaScript library ...

How to get the src attribute value, url, and then use the Ajax library tools to query that url and save this result where you want to do it?

The specific details will vary depending on the library used.

-2
Sep 29 '08 at 16:32
source share

Not sure why you need it?

Another way would be to hold the script in a hidden element somewhere and use Eval to run it. You can then request the properties of the innerHtml objects.

-3
Sep 29 '08 at 12:21
source share



All Articles