Michael Samuel Michael Samuel - 3 months ago 14
HTML Question

If condition load external javascript script

I have the following DIV:

<div id="top-ad"></div>


I want to load an external advertisement javascript script if the browser size is higher than 728. So, I need something like this:

<div id="top-ad">
<script>
if(window.innerWidth >= 728) {
<script src="//go.*****.com/?id=****"></script>
}
</script>
</div>


Of course the above won't work. I tried to load the script asynchronously using Jquery like this:

<div id="top-ad">
<script>
if(window.innerWidth >= 728) {
$.getScript("//go.*****.com/?id=****");
}
</script>
</div>


I tried the above method but I get the following error:


Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.


I don't have access to the DOM elements inside the loaded script and they are actually dynamic and I'm not allowed to alter them. Is there a way to load the script inside the
div
element based on the if condition?

Answer

Since the script you're loading uses document.write(), you have to use document.write to add the script in your if statement.

if (window.innerWidth >= 728) {
    document.write('<script src="//go.*****.com/?id=****"></sc' + 'ript>');
}

Notice that you have to split up </script>, otherwise it will end the <script> tag that runs your script. See Why split the <script> tag when writing it with document.write()?