Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - Are dynamically inserted <script> tags meant to work?

I have some code where a <script type="text/javascript"> block is dynamically inserted.

This block contains a function, which has an <input type="button"> element above it (also dynamically inserted) call it with the onclick attribute.

However, it is not working, and Firebug says that the function is not defined when I attempt to click the button.

Is this expectable, and if so is there a workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're writing it to an innerHTML property, it won't work except for in IE when the DEFER attribute is present:

scriptParentNode.innerHTML = '<span/><script defer="defer" type="text/javascript">blah();</script>';

Your options are, a) use the DOM to create the element and append it:

var head = document.getElementsByTagName("head")[0];
var sTag = document.createElement("script");
sTag.type = "text/javascript";
sTag.text = "blah();";
head.appendChild(sTag);

or b) use document.write at the time your HTML is parsed (but not after!)

<head>
  <script type="text/javascript">
    document.write('<script type="text/javascript">blah();</script>');
  </script>
</head>

EDIT

Seeing as I was downvoted apparently for the information regarding the defer attribute being incorrect, I feel it necessary to post a working example from the MSDN documentation. Whilst it is true that IE removes NoScope elements from the beginning of an innerHTML string, it's possible to work around this by adding a scoped element to the beginning of the HTML string (example updated above):

<HTML>
<SCRIPT>
function insertScript(){
    var sHTML="<input type=button onclick=" + "go2()" + " value='Click Me'><BR>";
    var sScript="<SCRIPT DEFER>";
    sScript = sScript + "function go2(){ alert('Hello from inserted script.') }";
    sScript = sScript + "</SCRIPT" + ">";
    ScriptDiv.innerHTML = sHTML + sScript;
}    
</SCRIPT>
<BODY onload="insertScript();">
    <DIV ID="ScriptDiv"></DIV>
</BODY>
</HTML>

Feel free to actually click the "Show me" button in the MSDN documentation for a working example. [link]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...