简体   繁体   English

HTML中script元素的charset属性的目的是什么?

[英]What is the purpose of charset attribute of script element in HTML?

In HTML, script element has optional charset attribute. 在HTML中,script元素具有可选的charset属性。

What is the purpose of it? 它的目的是什么?

When is it useful? 什么时候有用?

If your javascript files are encoded with a different encoding than the page is using, you can use the charset attribute to tell the browser how to interpret it. 如果您的javascript文件使用与页面使用的编码不同的编码进行编码,则可以使用charset属性告诉浏览器如何解释它。

For example, if the page is using Latin1 , but the JS file was created with UTF-8 . 例如,如果页面使用Latin1 ,但JS文件是使用UTF-8创建的。

The purpose of the charset parameter is to specify the encoding of the external script in cases where the encoding is not specified at the HTTP protocol level. charset参数的目的是在HTTP协议级别未指定编码的情况下指定外部脚本的编码。 It is not meant to override encoding information in HTTP headers, and it does not do that. 并不意味着覆盖HTTP头中的编码信息,并且它不会这样做。

This is useful when the author cannot control HTTP headers and the headers do not specify character encoding. 当作者无法控制HTTP标头且标头未指定字符编码时,这非常有用。 It is also useful for offline files, such as in a local copy of a web page accessed directly, not via an HTTP server, so that no HTTP headers exist. 它对于脱机文件也很有用,例如在直接访问的网页的本地副本中,而不是通过HTTP服务器,因此不存在HTTP标头。

In practice, it is not very useful. 在实践中,它不是很有用。 If you need to use non-Ascii characters in a JavaScript file, you can use UTF-8 encoding. 如果需要在JavaScript文件中使用非Ascii字符,则可以使用UTF-8编码。 If you use UTF-8 with a leading BOM, the BOM acts as a useful indicator that lets browsers infer the encoding. 如果您使用带有前导BOM的UTF-8,则BOM会充当一个有用的指标,让浏览器可以推断出编码。 But it does not hurt to additionally use charset=utf-8 . 但是额外使用charset=utf-8并没有什么坏处。

Each JavaScript file is a separate element from page, after all you can even load JS from some remote author's server that otherwise have no relations to your page at all. 每个JavaScript文件都是一个独立于页面的元素,毕竟你甚至可以从一些远程作者的服务器加载JS,否则它与你的页面根本没有任何关系。 Just as with any other external element, you can manually specify "charset" if remote server returns wrong charset for some reason or just to be sure. 与任何其他外部元素一样,如果远程服务器由于某种原因返回错误的字符集或者只是为了确定,您可以手动指定“charset”。

Also, if you have write access to this JS file yourself, you may want to replace all non-ASCII with Unicode position escapes - this will guarantee that symbols will always be interpreted correctly, no matter what encoding is specified in headers. 此外,如果您自己具有对此JS文件的写入权限,则可能需要将所有非ASCII替换为Unicode位置转义 - 这将保证无论头部中指定的编码是什么,都将始终正确解释符号。 Some JS minifiers, like Google Closure Compiler, can do it for you automatically. 一些JS minifiers,如Google Closure Compiler,可以自动为您完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM