Look at the reproduced code first
1, gb2312.html The file is encoded as gb2312
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="gb2312"/>
<style>
p {
color: red;
}
</style>
</head>
<body>
<button onclick="loadJS('utf8.js', 'utf-8')">Test</button>
<script>
function loadJS(src, charset) {
var script = document.createElement('script');
script.src = src;
script.charset = charset;
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}
</script>
</body>
</html>
2. utf8.js The file encoding is utf-8
The code copy is as follows:
var p = document.createElement('p');
p.innerHTML = 'IE cache causes garbled code';
document.body.appendChild(p);
The loadJS function dynamically creates a script, sets src, and adds it to the head after charset. Here, each click of the button will introduce utf8.js to the page. The code in utf.js will create a p element to set a piece of text and then add it to the body.
When you click the button for the first time, the text will be displayed normally.
After the second time, the text encoding was incorrect.
As shown
If the script tag is not a dynamically created script tag and is written directly on the html page, there is no problem.
The code copy is as follows:
<script type="text/javascript" src="utf8.js" charset="utf-8"></script>
If you use document.write to load js resources, the bug will not occur.
The code copy is as follows:
<script>
function loadByWrite(url, charset) {
var str = '<script type="text/javascript"' + ' src="' + url + '" charset="' + charset + '"><' + '/script>';
document.write(str);
}
</script>
<script>
loadByWrite('utf8.js', 'utf-8')
</script>
The solution is to replace the assignment order of the src and charset attributes.
The code copy is as follows:
script.charset = charset;
script.src = src;
That is, assign a value to the charset first.