Home  >  Article  >  Web Front-end  >  How to Handle Document Write Execution Failure After Asynchronous Script Loading?

How to Handle Document Write Execution Failure After Asynchronous Script Loading?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 14:13:30141browse

How to Handle Document Write Execution Failure After Asynchronous Script Loading?

Document Write Execution Failure After Asynchronous Script Loading

When loading a script asynchronously, the loaded script runs after the document has been completely parsed and closed. This limitation prevents the use of document.write() from within the loaded script.

Reason for the Error

The error message "It isn't possible to write into a document from an asynchronously-loaded external script" indicates that the attempt to write to the document using document.write() failed because the script was loaded after the document was closed.

Alternative DOM Manipulation

To address this issue, you'll need to replace any document.write() statements with explicit DOM manipulation. This involves creating DOM elements and inserting them into a parent element using methods like:

  • .appendChild()
  • .insertBefore()
  • .innerHTML

Example

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

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

You would use the following code in a dynamically loaded script:

<code class="javascript">var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);</code>

Alternatively, you could set the innerHTML of the container:

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

By replacing document.write() statements with these alternative DOM manipulation techniques, you can ensure the successful execution of your asynchronously-loaded scripts while still achieving the desired document modifications.

The above is the detailed content of How to Handle Document Write Execution Failure After 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