Home >Web Front-end >JS Tutorial >How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?

How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 20:50:02676browse

How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?

Including External Scripts Dynamically with Variable URLs

When dynamically adding script tags to a webpage, it's essential to consider scripts with src attributes that may include document.write commands. This can disrupt the normal loading behavior.

The Issue

In ordinary scenarios, using the following code to include a script from "source.js" works well:

<script type="text/javascript" src="source.js"></script>

However, "source.js" may contain the following unusual content:

document.write('<script type="text/javascript">')
document.write('alert("hello world")')
document.write('</script>')
document.write('<p>goodbye world</p>')

The Solution

Using the ordinary method will not handle this scenario correctly. Instead, you can use the following technique to dynamically add scripts with variable srcs:

var my_awesome_script = document.createElement('script');

my_awesome_script.setAttribute('src','http://example.com/site.js');

document.head.appendChild(my_awesome_script);

This method creates a new script element, sets its src attribute, and appends it to the of the document. It works even if the script's src includes document.write commands.

The above is the detailed content of How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?. 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