Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute <script> code in a javascript append

I'm working with a plugin that is only Javascript. I need to have it dynamically create a DIV element with an advertisement in it.

I can't figure out why this doesn't work:

$(this).append('<div class="overlay-background">Advertisement

     <script type="text-javascript">

          GA_googleFillSlot("blog_landing_right_rectangle_300x250");

     </script>'

It results in the element created with "Hello World" but it does not execute the GA-googleFillSlot function.

like image 923
user734063 Avatar asked Jan 11 '13 00:01

user734063


People also ask

What is append item in JavaScript?

append() method inserts a set of Node objects or string objects after the last child of the Element . String objects are inserted as equivalent Text nodes.

How do you add a script?

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 append in HTML?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')


3 Answers

appending HTML into the DOM does not cause the browser to evaluate any script tags in said appended HTML.

If you really wanted to, you could evaluate the javascript by using eval():

eval($(this).find("script").text());
like image 83
wless1 Avatar answered Sep 17 '22 12:09

wless1


I know this is an old question but I've had a similar problem today. The solution was using createContextualFragment.

My code looks something like this:

var tagString = '<script async type="text/javascript" src="path_to_script"></script>';

var range = document.createRange();
range.selectNode(document.getElementsByTagName("BODY")[0]);
var documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);
like image 37
temo Avatar answered Sep 19 '22 12:09

temo


This code works in my browser.

$('body').append('<script>alert("test");<' + '/' + 'script>');

so it might be that $(this) is what is actually causing your problem.

Can you replace it with 'body' and see if it works like that?

like image 38
Azder Avatar answered Sep 19 '22 12:09

Azder