Reputation: 3977
I am trying to create script tags dynamically under my page using javascript. So far I am able to create it, able to set its type and src. Now my question is, is there any way that instead of defining the src to a different page can I assign its content on the same page? Let me write my code to make it make more sense:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'custom.js';
Now is there any way I can assign it the content as well by doing something like this:
script.content = 'document.write("stackoverflow")';
script.html = 'document.write("stackoverflow")';
I am not sure whether they exist or not, but just guessing if i can do something like this.
Upvotes: 22
Views: 37285
Reputation: 41
Scripts can be read from or written to using 'scripts.text'. It's part of the script Data Object Model (DOM). And for some reason or another, it is different than other HTML tags. Example: 'myScript.innerHTML' tends not to work, but 'scripts.namedItem("myScript").text' does.
<p>Change scripts.text <a href="https://www.w3schools.com/jsref/prop_script_text.asp">https://www.w3schools.com/jsref/prop_script_text.asp</a>
</p>
<p>Script Object <a href="https://www.w3schools.com/jsref/dom_obj_script.asp">https://www.w3schools.com/jsref/dom_obj_script.asp</a>
</p>
<canvas id="Canvas1" style="border: 5px solid cyan"></canvas>
<p id="Para1">...</p>
<button onclick="ChangeScript()">Change Script</button>
<button onclick="DrawIt()">Drawit</button>
<button onclick="para1.innerHTML=script1.text;">Show Script</button>
<script id="Script1"></script>
<script>
function ChangeScript() {
script1.text = "function DrawIt(){canvas1.fillRect(1,2,30,40)}"
}
//Note: changing the script text more than once may not work.
canvas1 = document.getElementById("Canvas1").getContext("2d");
script1 = document.scripts.namedItem("Script1");
para1 = document.getElementById("Para1")
</script>
<a href="http://www.w3schools.com/code/tryit.asp?filename=FCR1ZI3MBN77">Try it Yourself, Change scripts.text</a>
Upvotes: 4
Reputation: 147383
You can do:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'alert("hello world")';
document.body.appendChild(script_tag);
In practice, whether you set the type property or not is likely irrelevant, but it gives one a warm inner glow.
Upvotes: 61