Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking document.write()

This code does not work:

<div class="pix"><div id="addTimestamp"></div></div>
<script type="text/javascript">
(function () {
    var date = new Date(), 
        timestamp = date.getTime(),
        newScript = document.createElement("script");

    newScript.type = 'text/javascript';
    newScript.src = 'someUrl=' + timestamp + '?';
    document.getElementById('addTimestamp').appendChild(newScript);
}())
</script>

The dynamic script adds document.write(someCode which loads banners). But in Firebug I have an error:

Invoking document.write() from asynchronously-loaded external script was ignored.

like image 301
levon Avatar asked Aug 31 '11 10:08

levon


2 Answers

Add this:

newScript.async = false;

Your script needs to load synchronously for document.write() to work (see https://developer.mozilla.org/En/HTML/Element/Script#attr-async). As you have it now, the script will load whenever the browser has time for it - so you cannot know where your HTML from document.write() will be inserted. The browser decided to ignore your document.write() call to prevent worse issues.

like image 171
Wladimir Palant Avatar answered Nov 16 '22 23:11

Wladimir Palant


document writing javascript causes the html parser to fail when seeing try

document.getElementById('addTimestamp').innerHTML = '<script type="text/javascript"     src="someUrl=' + timestamp + '?"' + 'charset="utf-8"></sc' + 'ript>';

However if you want to insert a script tag in in the DOM you need to also be certain the DOM is loaded.

like image 1
James Kyburz Avatar answered Nov 16 '22 23:11

James Kyburz