Home > Article > Web Front-end > Why is document.write() Restricted in Asynchronously Loaded Scripts?
Execution Restrictions in Asynchronously Loaded Scripts: Understanding document.write() Limitations
Attempting to write to a document from a script loaded asynchronously raises a console message, "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." This message may appear despite the expected behavior of the script, leaving developers puzzled.
Why the Restriction Exists
Asynchronously loaded scripts often execute after the document has been parsed and closed. Consequently, using document.write() from such scripts becomes problematic because the document is no longer open for writing.
Solution: Explicit DOM Manipulation
Instead of using document.write(), developers must explicitly manipulate the DOM in asynchronously loaded scripts. This involves creating DOM elements and inserting them into the desired parent element using methods such as .appendChild(), .insertBefore(), or setting .innerHTML.
Example: DOM Manipulation
To illustrate, consider the following inline script:
<div id="container"> <script> document.write('<span style="color:red;">Hello</span>'); </script> </div>
In an asynchronously loaded script, this code could be replaced with:
var container = document.getElementById("container"); var content = document.createElement("span"); content.style.color = "red"; content.innerHTML = "Hello"; container.appendChild(content);
Alternatively, since the container is empty, the following simplified code could be used:
var container = document.getElementById("container"); container.innerHTML = '<span style="color:red;">Hello</span>';
By adopting these DOM manipulation techniques, developers can effectively write to documents from asynchronously loaded scripts, avoiding the limitations imposed by document.write().
The above is the detailed content of Why is document.write() Restricted in Asynchronously Loaded Scripts?. For more information, please follow other related articles on the PHP Chinese website!