Writing content in the Script Tags section

I am trying to create script tags dynamically below my page using javascript. For now, I can create it to set its type and src. Now my question is, is there a way so that instead of defining src on another page, I can assign its content on the same page? Let me write my code to make it clearer:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'custom.js';

      

Now you can assign it to the content in some way by doing something like this:

script.content = 'document.write("stackoverflow")';
script.html = 'document.write("stackoverflow")';

      

I'm not sure if they exist or not, but just wondering if I can do something like this.

+3


source to share


2 answers


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 the type property is set or not is probably irrelevant, but it gives a warm inner glow.

+11


source


Scripts can be read or written using "scripts.text". It is part of the script data object model (DOM). And for one reason or another, it is different from other HTML tags. Example: "myScript.innerHTML" tends to not 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>
      

Run codeHide result


+2


source







All Articles