I work with a plugin that is Javascript only. I need it to dynamically create a div element with ads in it.
I can not understand why this does not work:
$(this).append('<div class="overlay-background">Advertisement <script type="text-javascript"> GA_googleFillSlot("blog_landing_right_rectangle_300x250"); </script>'
The result is an element created using "Hello World", but it does not perform the GA-googleFillSlot function.
Adding HTML to the DOM does not force the browser to evaluate script tags in the specified added HTML.
If you really want to, you can evaluate javascript using eval() :
eval()
eval($(this).find("script").text());
This code works in my browser.
$('body').append('<script>alert("test");<' + '/' + 'script>');
so it may be that $(this) is what actually causes your problem.
$(this)
You can replace it with 'body' and see if it works like this?
'body'
I know this is an old question, but I had a similar problem today. The solution was to use 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);
One workaround in your case could be to add a fake image with the onload event:
<img src="blank.gif" onload="GA_googleFillSlot('blog_landing_right_rectangle_300x250')" />
Try:
s = '<' + 'script type="text-javascript">' + 'GA_googleFillSlot("blog_landing_right_rectangle_300x250");' + '<' + '/' + 'script>'; $(this).append(s);
UPD: alas, this will not work, use wless1 solution instead
since you are in javascript you can add and then execute the code:
$(this).append('<div class="overlay-background">Advertisement</div>'); GA_googleFillSlot("blog_landing_right_rectangle_300x250");