如何获取指定为标记的'src'的文件内容?

时间:2022-10-27 07:57:28

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.

我想获取“script.js”文件的内容。我正在考虑类似document.getElementById(“myscript”)。text但在这种情况下它不起作用。

16 个解决方案

#1


10  

You want to get the contents of the file http://www.example.com/script.js ? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.

您想获取文件http://www.example.com/script.js的内容吗?如果是这样,您可以转向AJAX方法来获取其内容,假设它与页面本身位于同一服务器上。

Could you elaborate on what you're trying to accomplish?

你能详细说明你想要完成的事情吗?

#2


8  

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

我知道它有点晚了,但有些浏览器支持标签LINK rel =“import”属性。

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

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.

对于其他人来说,ajax仍然是首选方式。

#3


6  

I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.

我不认为内容可以通过DOM获得。您可以获取src属性的值并使用AJAX从服务器请求文件。

#4


1  

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.

如果你想要src属性的内容,你必须做一个ajax请求并查看responsetext。如果你在哪里有js,你可以通过innerHTML访问它。

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

这可能是有趣的:http://ejohn.org/blog/degrading-script-tags/

#5


1  

I had the same problem. There doesn't seem to be a way (short of ajax) to solve this in html files. But when I'm in php, at least, the following has proved very helpful:

我有同样的问题。在html文件中似乎没有办法(缺少ajax)来解决这个问题。但是当我在php中时,至少,以下内容证明非常有用:

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

Then you can grab the contents of the script tag with a normal getElementById('myScript').text;

然后你可以用普通的getElementById('myScript')来获取脚本标签的内容。

#6


0  

.text did get you contents of the tag, it's just that you 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 would follow the link and make an ajax request for it.

.text确实为你提供了标签的内容,只是你的开放标签和结束标签之间没有任何内容。您可以使用.src获取元素的src属性,然后如果您想获取javascript文件,您将按照链接并为其发出ajax请求。

#7


0  

In a comment to my previous answer:

在对我之前的回答的评论中:

I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)

我想存储脚本的内容,以便我可以缓存它并在一段时间后直接使用它,而不必从外部Web服务器(不在与页面相同的服务器上)获取它

In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.

在这种情况下,最好使用服务器端脚本来获取和缓存脚本文件。根据您的服务器设置,您可以只是忘记文件(如果您希望更改,则定期通过cron)或使用您选择的语言中的小脚本执行类似操作。

#8


0  

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

您想使用innerHTML属性来获取脚本标记的内容:

document.getElementById("myscript").innerHTML

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

但正如@olle在另一个回答中所说,您可能希望阅读:http://ejohn.org/blog/degrading-script-tags/

#9


0  

yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use jQuery.load(...), the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <br> into your (scriptNode).innerText, and things like that. Then, if you use jQuery.getScript(...), the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)

是的,Ajax就是这样做的方式,就像接受的答案一样。如果你了解细节,那就有很多陷阱。如果您使用jQuery.load(...),则假定错误的内容类型(html而不是application / javascript),这可能会通过将不需要的
放入您的(scriptNode).innerText以及类似的东西来搞乱。 。然后,如果您使用jQuery.getScript(...),则会立即执行下载的脚本,这可能不是您想要的(可能会破坏您要加载文件的顺序,以防您有多个。)

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

我发现最好使用jQuery.ajax和dataType:“text”

I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.

我在带有框架集的项目中使用了这种Ajax技术,其中框架集和/或几个框架需要相同的JavaScript,以避免服务器多次发送该JavaScript。

Here is code, tested and working:

这是代码,测试和工作:

<!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

相关问题

#10


0  

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.

tl; dr脚本标签不受CORS和同源策略的约束,因此javascript / DOM无法访问通过

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.

使用以下代码(如其他问题“使用XHR / AJAX”中所述),可以对文档中的所有非内联脚本标记执行另一个请求。

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

所以我不会重复这一点,而是希望通过这个答案添加到这个问题的方面

#11


-1  

If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.

如果您想要访问

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

它将允许您获取每个脚本属性。

If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.

如果它是您之后的example.js文件内容,那么您可以触发AJAX请求来获取它。

#12


-1  

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

如果提供了src属性,则需要用户代理忽略元素的内容,如果需要从外部脚本访问它,那么您可能做错了。

Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.

更新:我看到您添加了一个注释,表示您希望缓存脚本并在以后使用它。到底是什么?假设您的HTTP缓存友好,那么您的缓存需求可能已经由浏览器处理。

#13


-1  

I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.

我建议这个问题的答案是使用DOM元素的“innerHTML”属性。当然,如果脚本已加载,则无需进行Ajax调用即可获取它。

So Sugendran should be correct (not sure why he was voted down without explanation).

所以Sugendran应该是正确的(不确定为什么他在没有解释的情况下被投票)。

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

The innerHTML property of the script element should give you the scripts content as a string provided the script element is:

如果脚本元素是,则script元素的innerHTML属性应该为脚本提供脚本内容:

  • an inline script, or
  • 内联脚本,或
  • that the script has loaded (if using the src attribute)
  • 脚本已加载(如果使用src属性)

olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.

olle也给出了答案,但我觉得它“混乱”他建议首先需要通过ajax加载,我认为他的意思是“内联”而不是之间。

if you where to have the js between and you could access it through innerHTML.

如果你在哪里有js,你可以通过innerHTML访问它。


Regarding the usefulness of this technique:

关于这种技术的用处:

I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.

在获得未包含在我自己的脚本中的“未定义变量”(例如从工具栏或扩展中注入错误的脚本)后,我已经尝试将此技术用于客户端错误日志记录(javascript异常) - 所以我不这样做认为这是一个出路的想法。

#14


-2  

Using 2008-style DOM-binding it would rather be:

使用2008风格的DOM绑定它宁愿:

document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");

#15


-2  

Hopefully you are already using some JavaScript library...

希望你已经在使用一些JavaScript库......

What about getting the src attribute's value, the URL, and then use your library's Ajax tools to make a request to that URL and save that result wherever you are desiring to do so?

如何获取src属性的值,URL,然后使用库的Ajax工具向该URL发出请求并将结果保存到您希望的位置?

The specific details would vary depending on the library you are using.

具体细节将根据您使用的库而有所不同。

#16


-3  

Not sure why you would need to do this?

不确定为什么你需要这样做?

Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

另一种方法是将脚本保存在某个隐藏元素中并使用Eval运行它。然后,您可以查询对象innerHtml属性。

#1


10  

You want to get the contents of the file http://www.example.com/script.js ? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.

您想获取文件http://www.example.com/script.js的内容吗?如果是这样,您可以转向AJAX方法来获取其内容,假设它与页面本身位于同一服务器上。

Could you elaborate on what you're trying to accomplish?

你能详细说明你想要完成的事情吗?

#2


8  

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

我知道它有点晚了,但有些浏览器支持标签LINK rel =“import”属性。

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

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.

对于其他人来说,ajax仍然是首选方式。

#3


6  

I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.

我不认为内容可以通过DOM获得。您可以获取src属性的值并使用AJAX从服务器请求文件。

#4


1  

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.

如果你想要src属性的内容,你必须做一个ajax请求并查看responsetext。如果你在哪里有js,你可以通过innerHTML访问它。

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

这可能是有趣的:http://ejohn.org/blog/degrading-script-tags/

#5


1  

I had the same problem. There doesn't seem to be a way (short of ajax) to solve this in html files. But when I'm in php, at least, the following has proved very helpful:

我有同样的问题。在html文件中似乎没有办法(缺少ajax)来解决这个问题。但是当我在php中时,至少,以下内容证明非常有用:

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

Then you can grab the contents of the script tag with a normal getElementById('myScript').text;

然后你可以用普通的getElementById('myScript')来获取脚本标签的内容。

#6


0  

.text did get you contents of the tag, it's just that you 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 would follow the link and make an ajax request for it.

.text确实为你提供了标签的内容,只是你的开放标签和结束标签之间没有任何内容。您可以使用.src获取元素的src属性,然后如果您想获取javascript文件,您将按照链接并为其发出ajax请求。

#7


0  

In a comment to my previous answer:

在对我之前的回答的评论中:

I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)

我想存储脚本的内容,以便我可以缓存它并在一段时间后直接使用它,而不必从外部Web服务器(不在与页面相同的服务器上)获取它

In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.

在这种情况下,最好使用服务器端脚本来获取和缓存脚本文件。根据您的服务器设置,您可以只是忘记文件(如果您希望更改,则定期通过cron)或使用您选择的语言中的小脚本执行类似操作。

#8


0  

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

您想使用innerHTML属性来获取脚本标记的内容:

document.getElementById("myscript").innerHTML

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

但正如@olle在另一个回答中所说,您可能希望阅读:http://ejohn.org/blog/degrading-script-tags/

#9


0  

yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use jQuery.load(...), the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <br> into your (scriptNode).innerText, and things like that. Then, if you use jQuery.getScript(...), the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)

是的,Ajax就是这样做的方式,就像接受的答案一样。如果你了解细节,那就有很多陷阱。如果您使用jQuery.load(...),则假定错误的内容类型(html而不是application / javascript),这可能会通过将不需要的
放入您的(scriptNode).innerText以及类似的东西来搞乱。 。然后,如果您使用jQuery.getScript(...),则会立即执行下载的脚本,这可能不是您想要的(可能会破坏您要加载文件的顺序,以防您有多个。)

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

我发现最好使用jQuery.ajax和dataType:“text”

I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.

我在带有框架集的项目中使用了这种Ajax技术,其中框架集和/或几个框架需要相同的JavaScript,以避免服务器多次发送该JavaScript。

Here is code, tested and working:

这是代码,测试和工作:

<!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

相关问题

#10


0  

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.

tl; dr脚本标签不受CORS和同源策略的约束,因此javascript / DOM无法访问通过

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.

使用以下代码(如其他问题“使用XHR / AJAX”中所述),可以对文档中的所有非内联脚本标记执行另一个请求。

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

所以我不会重复这一点,而是希望通过这个答案添加到这个问题的方面

#11


-1  

If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.

如果您想要访问

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

它将允许您获取每个脚本属性。

If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.

如果它是您之后的example.js文件内容,那么您可以触发AJAX请求来获取它。

#12


-1  

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

如果提供了src属性,则需要用户代理忽略元素的内容,如果需要从外部脚本访问它,那么您可能做错了。

Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.

更新:我看到您添加了一个注释,表示您希望缓存脚本并在以后使用它。到底是什么?假设您的HTTP缓存友好,那么您的缓存需求可能已经由浏览器处理。

#13


-1  

I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.

我建议这个问题的答案是使用DOM元素的“innerHTML”属性。当然,如果脚本已加载,则无需进行Ajax调用即可获取它。

So Sugendran should be correct (not sure why he was voted down without explanation).

所以Sugendran应该是正确的(不确定为什么他在没有解释的情况下被投票)。

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

The innerHTML property of the script element should give you the scripts content as a string provided the script element is:

如果脚本元素是,则script元素的innerHTML属性应该为脚本提供脚本内容:

  • an inline script, or
  • 内联脚本,或
  • that the script has loaded (if using the src attribute)
  • 脚本已加载(如果使用src属性)

olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.

olle也给出了答案,但我觉得它“混乱”他建议首先需要通过ajax加载,我认为他的意思是“内联”而不是之间。

if you where to have the js between and you could access it through innerHTML.

如果你在哪里有js,你可以通过innerHTML访问它。


Regarding the usefulness of this technique:

关于这种技术的用处:

I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.

在获得未包含在我自己的脚本中的“未定义变量”(例如从工具栏或扩展中注入错误的脚本)后,我已经尝试将此技术用于客户端错误日志记录(javascript异常) - 所以我不这样做认为这是一个出路的想法。

#14


-2  

Using 2008-style DOM-binding it would rather be:

使用2008风格的DOM绑定它宁愿:

document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");

#15


-2  

Hopefully you are already using some JavaScript library...

希望你已经在使用一些JavaScript库......

What about getting the src attribute's value, the URL, and then use your library's Ajax tools to make a request to that URL and save that result wherever you are desiring to do so?

如何获取src属性的值,URL,然后使用库的Ajax工具向该URL发出请求并将结果保存到您希望的位置?

The specific details would vary depending on the library you are using.

具体细节将根据您使用的库而有所不同。

#16


-3  

Not sure why you would need to do this?

不确定为什么你需要这样做?

Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

另一种方法是将脚本保存在某个隐藏元素中并使用Eval运行它。然后,您可以查询对象innerHtml属性。