Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Content Under Script Tags

Tags:

javascript

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.

like image 506
Aman Virk Avatar asked Mar 09 '12 06:03

Aman Virk


People also ask

What do you write in a script tag?

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.

How can I get script tag 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?

Can we write script tag inside script tag?

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).

Where do you write script tags?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


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

like image 187
RobG Avatar answered Sep 22 '22 18:09

RobG