Home > Web Front-end > JS Tutorial > How to Safely Include Dynamic Scripts with Uncertain Src Content?

How to Safely Include Dynamic Scripts with Uncertain Src Content?

Linda Hamilton
Release: 2024-10-29 17:41:02
Original
503 people have browsed it

How to Safely Include Dynamic Scripts with Uncertain Src Content?

Including Dynamic Scripts with Uncertain Src Content

Question:

How can I dynamically add a script tag with an unrestrained src that may contain document.write calls?

Explanation:

In scripts with uncontrolled src attributes, the content may include document.write calls, which can interfere with traditional script tag loading.

Solution:

To circumvent this issue, create a new script element manually:

var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
Copy after login

Append the newly created script element to the head of the document:

document.head.appendChild(my_awesome_script);
Copy after login

This method ensures that the script is loaded asynchronously without interfering with the document flow.

The above is the detailed content of How to Safely Include Dynamic Scripts with Uncertain Src Content?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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