Frnnd Sgz
Frnnd Sgz

Reputation: 328

Problems with "document.write" using RequireJS modules

I have a module that needs to execute a document.write action in order to print a banner once the page is loaded.

If I do this using the old-school way, I get no problems. The banner is printed inside the div.

<div id="banner">
    <script> addAdvert() </script>
</div>

<script>
function addAdvert(){
  srcScript = 'http://www.urltoscript.js';
  document.write('<script type=\"text/javascript\" src=\"'+srcScript+'" ><\/script>');
}
</script>

But If I try this using a require js module (kind of this):

addAvert: function() {
             var srcScript = options.urltoScript
             document.write('<script type=\"text/javascript\" src=\"'+srcScript+'" ><\/script>');
}

It executes the document.write and render all the document printing only the banner on the entire document...

I have try this alternative:

addAvert: function() {
    var srcScript = options.urltoScript

          var bsa = document.createElement('script');
             bsa.type = 'text/javascript';
             bsa.async = true;
             bsa.src = srcScript;
             $("#banner").append(bsa);
 }

Upvotes: 0

Views: 684

Answers (1)

Louis
Louis

Reputation: 151531

Judging by your comment, the script which you are trying to load from the imaginary URL http://www.urltoscript.js also uses document.write. Either you should change this script to not use document.write or you should abandon the idea of loading it asynchronously, because document.write does not work reliably when invoked asynchronously.

You've already discovered when you tried require([bsa.src]) (as you mentioned in a comment) that you cannot call document.write from a script that is loaded asynchronously. (Also note that just doing require([bsa.src]) is not going to work unless the source code at the other end is an AMD-module or you defined a shim for it.)

Your first attempt at loading through RequireJS did not produce an error message about document.write being loaded asynchronously because the script element that loads it is not itself asynchronous. However, it completely blanked your page. This is because if you call document.write after the page has finished loading, the browser may implicitly call document.open and this may blank your page.

The upshot here is that you cannot reliably use document.write with asynchronous code.

Upvotes: 1

Related Questions