Sometimes we need to dynamically add suitable js, because sometimes we don’t need to load all js in order to improve efficiency. The following are 4 commonly used methods
1. Direct document.write
1 2 3 |
|
2. Dynamically change the src attribute of an existing script
1 2 3 4 |
|
3. Dynamically create script element
1 2 3 4 5 6 7 |
|
These three methods are executed asynchronously
4. Principle: Use XMLHTTP to obtain the content of the script , and then create a Script object.
Note: a.js must be saved in UTF8 encoding to avoid errors. Because the server and XML use UTF8 encoding to transmit data.
Main page code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
The dynamic loading of a JS script is now completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
The above is the detailed content of Code summary of four commonly used JavaScript dynamic loading methods. For more information, please follow other related articles on the PHP Chinese website!