How to execute <script> code in a javascript append

我们两清 提交于 2019-11-27 23:44:50

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());

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?

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

One workaround in your case could be to append a fake image with an onload event:

<img src="blank.gif" onload="GA_googleFillSlot('blog_landing_right_rectangle_300x250')" />

Please try:

s = '<' + 'script type="text-javascript">' +
    'GA_googleFillSlot("blog_landing_right_rectangle_300x250");' +
    '<' + '/' + 'script>';
$(this).append(s);

UPD: alas, this won't work, please use wless1's solution instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!