1
votes

I am having an issue trying to dynamically add and execute a div containing inline Javascript?

var div = document.createElement('DIV');                
div.onready = (function(name) { return GA_vitalFillSlot(name); })(wallpaper_ads.custom[i]);
document.getElementById('wallpaperAdContainer').appendChild(div);

where wallpaper_ads.custom[i] contains a string, e.g. 'BMX_wallpaper_2328x1080_homepage'. Above code does not work. But it works if I change GA_vitalFillSlot() to alert():

var div = document.createElement('DIV');                
div.onready = (function(name) { return alert(name); })(wallpaper_ads.custom[i]);
document.getElementById('wallpaperAdContainer').appendChild(div);

Also, doing something like this doesn't work either:

var js = document.createElement('SCRIPT');
js.type = 'text/javascript';
js.innerHTML = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';
document.getElementById('wallpaperAdContainer').appendChild(js);

Any ideas what is wrong here?

3

3 Answers

1
votes

Either:

js.src = 'myCode.js';

or

js.text = 'alert("hey");';

Script inserted using innerHTML does not get executed.

1
votes

This line of code:

(function(name) { return GA_vitalFillSlot(name); })(wallpaper_ads.custom[i]);

is executing immediately setting the div.onready equal to the result of GA_vitalFillSlot(name). Change it so the onready points to a function:

div.onready = (function(name) { 
    return function() {
        GA_vitalFillSlot(name);
    };
})(wallpaper_ads.custom[i]);
0
votes

This should work

js.src = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';