Home > Web Front-end > JS Tutorial > Why is document.write() Restricted in Asynchronously Loaded Scripts?

Why is document.write() Restricted in Asynchronously Loaded Scripts?

Linda Hamilton
Release: 2024-10-20 14:09:02
Original
589 people have browsed it

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>
Copy after login

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);
Copy after login

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>';
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template