Forum Moderators: open

Message Too Old, No Replies

Conditionally loading 3rd party scripts

         

csdude55

11:10 pm on Aug 21, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm specifically wanted to load Google Ad Manager ONLY under certain conditions.

I haven't done this in a long time, but I think this is right?

if (condition) {
var scriptEle = document.createElement('script');

scriptEle.setAttribute('src', 'https://securepubads.g.doubleclick.net/tag/js/gpt.js');
scriptEle.setAttribute('type', 'text/javascript');
scriptEle.setAttribute('async', true);

document.body.appendChild(scriptEle);

// do stuff
}


Assuming so, would this be the correct way to also load Adsense?

if (condition) {
var scriptEle = document.createElement('script');

// GPT
scriptEle.setAttribute('src', 'https://securepubads.g.doubleclick.net/tag/js/gpt.js');
scriptEle.setAttribute('type', 'text/javascript');
scriptEle.setAttribute('async', true);

document.body.appendChild(scriptEle);

// Adsense
// note that I'm reusing scriptEle instead of a second var
scriptEle.setAttribute('src', 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-12345');

// do I actually need to set "type" and "async" again, since it's the same as above?
scriptEle.setAttribute('type', 'text/javascript');
scriptEle.setAttribute('async', true);

// note that Adsense uses "crossorigin", is this the right way to set it here?
scriptEle.setAttribute('crossorigin', 'crossorigin');

document.body.appendChild(scriptEle);

// do stuff
}