Home  >  Article  >  Web Front-end  >  How to Override document.write() Limitations in Asynchronous Script Loading?

How to Override document.write() Limitations in Asynchronous Script Loading?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-20 14:04:02478browse

How to Override document.write() Limitations in Asynchronous Script Loading?

Asynchronous Script Loading: Understanding document.write() Limitations

When executing scripts asynchronously, after the initial page load, it's essential to be aware of the limitations it poses on document manipulation. As stated in the console message, "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."

This means that using document.write() within such externally loaded scripts won't effectively write to the document, even though the script itself loads successfully. The reason lies in the fact that asynchronous scripts run after the document has been parsed and closed.

To address this issue, it's necessary to substitute document.write() with explicit DOM manipulations. Instead of writing directly to the document, create the desired DOM elements and append them to the document using methods like appendChild(), insertBefore(), or by setting the innerHTML property.

For instance, instead of using document.write() in an inline script:

<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>

In a dynamically loaded script, replace it with the following:

var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);

Alternatively, if there is no other content in the container, you can directly set the innerHTML property:

var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';

By following these guidelines, you can effectively manipulate the DOM from asynchronously loaded scripts without encountering the "Failed to execute 'write' on 'Document'" error.

The above is the detailed content of How to Override document.write() Limitations in Asynchronous Script Loading?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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