Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a <script> element to the DOM and execute its code?

I want to add a element into the existing DOM to have the javascript code run.

I did this with YUI:

var scriptNode = Y.Node.create('<script type="text/javascript" charset="utf-8">alert("Hello world!");<\/script>'); var headNode = Y.one('head'); headNode.append(scriptNode); 

It's successfully added to the DOM but it doesn't give me an alert.

Someone knows what the problem is?

like image 440
ajsie Avatar asked Jun 21 '11 22:06

ajsie


People also ask

How do you add an element to the DOM?

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

How do you add a script to a head tag?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do you execute a script tag?

The “script” tag JavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag. You can run the example by clicking the “Play” button in the right-top corner of the box above. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.

How do you add a script to markdown?

You have two options: You could include raw HTML <script> tags in your Markdown, or you could use MkDocs' extra_javascript setting to point to your own JavaScript file.


1 Answers

I have no idea how YUI's Node.create() function works, so no comment on that. But a simple cross-browser script is:

  window.onload = function() {     var s = document.createElement('script');     s.type = 'text/javascript';     var code = 'alert("hello world!");';     try {       s.appendChild(document.createTextNode(code));       document.body.appendChild(s);     } catch (e) {       s.text = code;       document.body.appendChild(s);     }   } 

The try..catch block is necessary as most browsers like the first method but some don't and throw an error. The second method covers those. You can also simply eval the code, which is more or less equivalent and what some libraries do.

like image 147
RobG Avatar answered Sep 26 '22 06:09

RobG