How can I get the content of the file specified as

2019-01-02 21:09发布

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 content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case.

标签: javascript
15条回答
步步皆殇っ
2楼-- · 2019-01-02 21:48

if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.

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

查看更多
冷夜・残月
3楼-- · 2019-01-02 21:50

I know it's a little late but some browsers support the tag LINK rel="import" property.

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

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

For the rest, ajax is still the preferred way.

查看更多
姐姐魅力值爆表
4楼-- · 2019-01-02 21:50

tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <script> tag, or it would break same-origin-policy.

long version: Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a <script> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <script src=[url]></script> would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS, to get the content.

With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.

function printScriptTextContent(script)
{
  var xhr = new XMLHttpRequest();
  xhr.open("GET",script.src)
  xhr.onreadystatechange = function () {
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      console.log("the script text content is",xhr.responseText);
    }
  };
  xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);

and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat

查看更多
登录 后发表回答