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

Viewed 105

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

I'd suggest to leave the script tag at the end of the page. However the solution could be the following:

const ad = document.getElementById('ad')
const script = document.createElement('script')
script.type = "text/javascript"
script.innerHTML = `
    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>');
`

ad.appendChild(script)

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

Related