Home  >  Article  >  Web Front-end  >  How to Dynamically Include Scripts with Uncontrolled `document.write()` Content?

How to Dynamically Include Scripts with Uncontrolled `document.write()` Content?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 22:28:03355browse

How to Dynamically Include Scripts with Uncontrolled `document.write()` Content?

Dynamically Adding Script Tags with Uncontrolled Source Content

Creating a script tag with a source external to your control can pose a challenge when the content includes code that utilizes document.write(). As noted, simply appending the script tag in the cannot support such content.

To overcome this, consider the following solution:

  1. Create a new script element using document.createElement('script').
  2. Assign the external source to the script's src attribute:
var my_awesome_script = document.createElement('script');

my_awesome_script.setAttribute('src','http://example.com/site.js');
  1. Append the script element to the of the document:
document.head.appendChild(my_awesome_script);

This method effectively includes the external script dynamically, allowing the included code to execute without any issues.

The above is the detailed content of How to Dynamically Include Scripts with Uncontrolled `document.write()` Content?. 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