I have a script tag which calls a remote JavaScript snippet through src, and writes it on the page, thus rendering a banner in the process.
I’m looking for a way to call the script, or insert the script via JavaScript. Right now it looks like this:
<div id="<?php print $banner_id; ?>" class="banner-responsive <?php print $breakpoints; ?>">
<script src="<?php print $url; ?>"></script>
</div>
This is the preferred method supplied by the banner vendor. I’m looking for a way to implement it more like this:
<div class="banner">
<div id="<?php print $banner_id; ?>">
<script type="text/javascript">
function banner_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = '<?php print $url; ?>';
var x = document.getElementById('<?php print $banner_id; ?>');
x.parentNode.appendChild(s);
}
if (window.attachEvent)
window.attachEvent('onload', banner_load);
else
window.addEventListener('load', banner_load, false);
</script>
</div>
</div>
This sort of works. It inserts the script tag, and calls the remote URL, but it does not execute the JS snippet received like it does in example 1, and because of that the banners do not appear. Is there a way for me to execute the script src at will?
What the src response could look like:
document.write("<a target='_blank' href='http://domain/?options'><img src='http://domain/whateever-930x180px.jpg' alt='Click here' /></a>");
I want to do this, so I can switch banners at specific moments, based on pre-defined break points. How would you go about this? Any thoughts?
Update: I don’t have any control over the output. It’s an external banner supplier. I take it that this is impossible?
You cannot dynamically load javascript that uses
document.write()and get the result you want.Dynamically loaded javascript runs AFTER the DOM has been loaded. When
document.write()is used after the DOM has been loaded, it clears the entire document and starts a new empty document. As such, it will not do what you want.If you want to dynamically load the Javascript, then you will need to use DOM manipulations (e.g.
document.createElement()andelem.appendChild()) to insert your banner into the existing DOM and not usedocument.write().document.write()is only useful for this type of problem when it is done inline with sequentially loaded javascript either inline or via<script>tags in the markup (not via dynamically loaded javascript).