Home  >  Article  >  Web Front-end  >  How to implement JS dynamic insertion of scripts and insertion of referenced external link scripts

How to implement JS dynamic insertion of scripts and insertion of referenced external link scripts

php中世界最好的语言
php中世界最好的语言Original
2018-05-28 14:15:462276browse

This time I will show you how to dynamically insert JS scripts and insert referenced external link scripts, and how to implement JS dynamically insert scripts and insert referenced external link scripts. What are the precautions?. Here are practical cases. Let’s take a look.

What is a js dynamically inserted script?

refers to a script that does not exist when the page is loaded, but can be modified at some point in the future. DOM dynamically added script. Same as working with HTML elements.

js There are also two ways to dynamically insert scripts: inserting JavaScript code and inserting external files.

1. Directly insert javascript code

<script type="text/javascript">
function sayHi() {
 alert("hi");
}
</script>

Logically speaking, the following DOM code is valid:

var script = document.createElement("script");
script.type = "text/javascript";
script.appendChild(document.createTextNode("function sayHi() {alert('hi');}"));
document.body.appendChild(script);

These DOM codes run normally in Firefox, Safari, Chrome and Opera. But in IE, it causes an error. IE treats