如何在 javascript 文件中设置 charset="utf-8"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44606147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:38:49  来源:igfitidea点击:

How to set charset="utf-8" in the javascript file itself

javascriptutf-8character-encoding

提问by Jehad Nasser

I am trying to set charset="utf-8" inside the javascript file itself, not in the script tag, I know that I can do this:

我试图在 javascript 文件本身中设置 charset="utf-8" ,而不是在脚本标签中,我知道我可以这样做:

<script type="text/javascript" charset="UTF-8" src="xyz.js"></script>

But unfortunately, this solution needs me to do the same step with hundreds of websites which are using the same script. so I am trying to set the charset in the javascript file itself. Is this possible?

但不幸的是,这个解决方案需要我对数百个使用相同脚本的网站执行相同的步骤。所以我试图在 javascript 文件本身中设置字符集。这可能吗?

thanks

谢谢

回答by Jehad Nasser

I found another way, so instead of declaring charset="UTF-8"for the script tag like this:

我找到了另一种方法,而不是charset="UTF-8"像这样声明脚本标签:

<script type="text/javascript" charset="UTF-8" src="xyz.js"></script>

I can declare the charset for the web page itself using meta tag, so I can append <meta charset="UTF-8">to the DOM dynamically, and end up with something like:

我可以使用元标记为网页本身声明字符集,这样我就可以<meta charset="UTF-8">动态地附加到 DOM,并最终得到如下内容:

<head>
...
  <meta charset="UTF-8">
...
</head>

回答by Iqon

I think you can't set this in the Javascript file itself. The browser need the charset to read the file. So without the charset the browser is not able to understand your file and therefore would not be able to read the charset definition

我认为您不能在 Javascript 文件本身中设置它。浏览器需要字符集来读取文件。因此,如果没有字符集,浏览器将无法理解您的文件,因此将无法读取字符集定义