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.
The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.
You can use native Javascript to do this! External tag can be loaded dynamically instead of inline. Then the code will be inserted between opening and closing tags. It works for me. is there some way to use this method to select script tags that have a specific type attribute?
The usual script tag (type text/javascript) is used to embed js inside markup. The tag itself is not valid js, so you cannot nest script tags (unless it's in an opaque context, such as a string).
Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With