Home > Web Front-end > JS Tutorial > body text

Solution to the encoding caused by dynamically creating scripts when caching js files in IE_javascript tips

WBOY
Release: 2016-05-16 16:50:09
Original
1175 people have browsed it

Let’s first look at the reproduction code

1, gb2312.html. The file is encoded as gb2312

Copy the code The code is as follows :








< body>

<script> <br>function loadJS(src, charset ) { <br>var script = document.createElement('script'); <br>script.src = src; <br>script.charset = charset; <br>var head = document.getElementsByTagName('head')[ 0]; <br>head.appendChild(script); <br>} <br></script>



2. utf8.js The file encoding is utf-8
Copy the code The code is as follows:

var p = document.createElement('p');
p.innerHTML = 'IE cache causes garbled characters';
document.body.appendChild(p);

loadJS function dynamics Create a script, set src, charset and add it to the head. Every time you click the button here, utf8.js will be introduced into 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 displays normally.

After the second time, the text encoding is incorrect.

As shown in the figure

Solution to the encoding caused by dynamically creating scripts when caching js files in IE_javascript tips

If it is not a dynamically created script tag and is written directly on the html page, there will be no such problem.
Copy code The code is as follows:



This bug will not occur if you use document.write to load js resources
Copy code The code is as follows:

<script> <br>function loadByWrite(url, charset) { <br> var str = '<script type="text/javascript"' ' src="' url '" charset="' charset '"><' '/script>'; <br>document.write(str) ; <br>} <br></script>
<script> <br>loadByWrite('utf8.js', 'utf-8') <br></script>

The solution is to change the order of assignment of the src and charset attributes.
Copy code The code is as follows:

script.charset = charset;
script.src = src;

That is, assign a value to charset first.
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template