0

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?

3
  • 1
    Or even if(innerWidth>=728) document.write('<script src="..."><'+'/script>');? Commented Aug 27, 2016 at 11:49
  • 1
    @NiettheDarkAbsol It is very bad practice to append scripts like that. Commented Aug 27, 2016 at 11:49
  • 1
    @SoftwareEngineer171 It is, I agree, but the script being appended itself uses document.write (as shown by the error message), so the only way to make that ad network's script work is to document.write it in. Commented Aug 27, 2016 at 11:50

1 Answer 1

4

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()?

Sign up to request clarification or add additional context in comments.

3 Comments

I have also another question, by splitting the closing script tag like this, doesn't the tag get broken?
No, because the concatenation puts it back together, so it's not broken when document.write() adds it to the document.
@MichaelSamuel I've added a link to a question that explains it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.