0

I want to display an advertisement in my page loaded with AJAX/jQuery-JSON.

  • The script:
  • The file xxxxx.js contains a document.write ();

How to integrate this script and make the document.write be interpreted. and why it does not work?

here is my test revealed that the script is executed because the alert ('hello 1') is displayed but not document.write that contains the alert ('hello 2');

Call the file directly into the DOM execute well "hello 1" and "hello 2"

test.js

alert("hello 1");
document.write('<scr'+'ipt type="text/javascript">alert("hello 2");</scr'+'ipt>');

index :

<body>
<script>
function loadScriptJs() {
var s = document.createElement('script'); 
s.src = 'test.js';  
s.type = 'text/javascript';
document.getElementById("pub").appendChild(s);
}
</script>
<div id="pub">
    PUB A AJOUTER CI DESSOUS EN JAVASCRIPT  :
    <!--  appel direct de la pub 
    <script src="test.js" type="text/javascript"></script> -->
</div>
<script> loadScriptJs(); </script>
</body>

1 Answer 1

1

When you add a script with appendChild, it's loaded asynchronously. So when your code in test.js runs, chances are the DOM is already constructed, and document.write will overwrite all page contents.

It looks like the most simple solution is to replace this:

<script> loadScriptJs(); </script>

with:

<script src="test.js"></script>

The other option is to not use document.write at all inside test.js. From loadScriptJs, set a callback for script load (s.onload = function() { /* loaded */ })), then inject the ad into the DOM from that callback.

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

2 Comments

sorry for my english :) thank you bfavaretto but I can not use the simple solution in order to make a hit for each load : I have to load the script each loading content, the function will be executed after loading my content
Okay, but then you can't use document.write in test.js. See my update.

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.