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

Time:09-11

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

CodePudding user response:

document.write can't be used on the owning document from an async script and injected scripts are always async.

(Also, is it atOptions or adOptions?)

document.querySelector('[id=ad]').insertAdjacentHTML('beforeend', `
<scr` `ipt type="text/javascript">
    atOptions = {
        'key' : '648ed94d49e39704aa01f7',
        'format' : 'iframe',
        'height' : 90,
        'width' : 728,
        'params' : {}
    };
<scr` `ipt>
<scr` `ipt type="text/javascript" src="http`   (location.protocol === 'https:' ? 's' : '')   `://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr` `ipt>`
);

CodePudding user response:

HTML5 does not allow script tags to be dynamically added using the innerHTML property therefore your code will not execute! Instead you could use appendChild.

target.appendChild('your script tag');
  • Related