document.write Not working when loading external Javascript source

Posted by jadent on Stack Overflow See other posts from Stack Overflow or by jadent
Published on 2013-11-04T15:39:49Z Indexed on 2013/11/04 15:53 UTC
Read the original article Hit count: 267

Filed under:

I'm trying to load an external JavaScript file dynamically into an HTML element to preview an ad tag. The script loads and executes but the script contains "document.write" which has an issue executing properly but there are no errors.

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
        <script type="text/javascript">
        $(function() {
            source = 'http://ib.adnxs.com/ttj?id=555281';

            // DOM Insert Approach
            // -----------------------------------
            var script = document.createElement('script');
                script.setAttribute('type', 'text/javascript');
                script.setAttribute('src', source);

            document.body.appendChild(script);
        });
        </script>
    </head>

<body>
</body>
</html>

I can get it to work if

  1. If i move the the source to the same domain for testing
  2. If the script was modified to use document.createElement and appendChild instead of document.write like the code above.

I don't have the ability to modify the script since it being generated and hosted by a 3rd party.

Does anyone know why the document.write will not work correctly? And is there a way to get around this?

Thanks for the help!

© Stack Overflow or respective owner

Related posts about JavaScript