Dynamically creating scripts that cause coding when caching js files in IE

  • 2020-03-30 02:49:02
  • OfStack

Let's look at the reproduction code

1, gb2312.html the file code is gb2312
<!DOCTYPE html> 
<meta charset="gb2312"/> 
p { 
color: red; 
<button onclick="loadJS('utf8.js', 'utf-8')"> test </button> 
function loadJS(src, charset) { 
var script = document.createElement('script'); 
script.src = src; 
script.charset = charset; 
var head = document.getElementsByTagName('head')[0]; 

2, utf8.js the file encoding is utf-8
var p = document.createElement('p'); 
p.innerHTML = 'IE The cache causes garbled code '; 

The loadJS function dynamically creates a script, sets SRC, and adds charset to the head. Each click here introduces utf8.js into the page, and the code in utf.js creates a p element and sets up a piece of text, and then adds it to the body.

The first time you click the button, the text displays normally.

After the second time, the text code is not correct.

As shown in figure

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/20140504103649.png? 201444103720 ">  

This is not a problem if the script tag is not created dynamically and written directly on the HTML page.
<script type="text/javascript" src="utf8.js" charset="utf-8"></script> 

This bug will not occur if the js resource is loaded in document.write mode
function loadByWrite(url, charset) { 
var str = '<script type="text/javascript"' + ' src="' + url + '" charset="' + charset + '"><' + '/script>'; 
loadByWrite('utf8.js', 'utf-8') 

The solution is to replace the assignment order of SRC and charset properties.
script.charset = charset; 
script.src = src; 

That is to assign a value to charset.

Related articles: