Reputation: 5263
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?
Upvotes: 1
Views: 3537
Reputation: 644
This should work
js.src = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';
Upvotes: 0
Reputation: 12440
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]);
Upvotes: 1
Reputation: 147343
Either:
js.src = 'myCode.js';
or
js.text = 'alert("hey");';
Script inserted using innerHTML does not get executed.
Upvotes: 1