Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-20 14:13:30
Original
135 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!