Search code examples
javascripthtmlads

How do I add script dynamically and run it. I am able to add it to my html code, but it is not executed


I have a blog (40+ articles) In each article, there is a div element with id="ad".

I want to write a script with will add the (another) script in that div, so ad will be displayed only there where the div is. My ad provider is adsterra.

I want to add the code below in my target element (div tag). This code is provided my ad provider.

<script type="text/javascript">
    atOptions = {
        'key' : '648ed94d49e39704aa01f7',
        'format' : 'iframe',
        'height' : 90,
        'width' : 728,
        'params' : {}
    };
    document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr' + 'ipt>');
</script>

I have done the following (which doesn't work).

document.getElementById('ad').innerHTML = `(the code above with correct escapes)`;

I have tried the following code too, which is again not working.

    var div = document.getElementById('ad');
    var ad = document.createElement('script');
    ad.text = `
    atOptions = {
        'key' : '648ed94d49e39704aa01f7',
        'format' : 'iframe',
        'height' : 90,
        'width' : 728,
        'params' : {}
    };
    document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr' + 'ipt>');
    `;
    
    div.appendChild(ad);

Solution

  • Ok, I wanted to do something such that I don't have to edit all 40+ articles to add code for an ad.

    I could not find a way to insert a script dynamically. Sometimes ad is displayed but out of place (and doesn't look good).

    I removed all the code related to ad, and just left with the code blog application without ads. Then I changed my view, and decided to edit the theme. My site is powered by Ghost, and I am using edition theme. I downloaded the current theme, and edited it to show an ad at the end of the article.

    Now, if I change the ad provider or what so ever, I will have to update the code at only the one place (in the theme).

    BTW, my site is https://blog.nirmites.com