Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare character encoding in an INDIVIDUAL JS file?

We can declare the character encoding in an INDIVIDUAL CSS file by codes below:

@charset "UTF-8";

My question is:

How to declare character encoding in an INDIVIDUAL JS file?

If I send a JS file to my friend, I hope he (she) can understand this JS file's character encoding from codes themselves when he (she) starts to browse or edit this JS file.

Thank you!

like image 596
weilou Avatar asked Jan 12 '12 10:01

weilou


1 Answers

You can't. You can, however, define it in the script tag that brings the file into the page, using the charset attribute. This must match the charset, if any, in the Content-Type that you serve the file with. Quoting:

The charset attribute gives the character encoding of the external script resource. The attribute must not be specified if the src attribute is not present. If the attribute is set, its value must be a valid character encoding name, must be an ASCII case-insensitive match for the preferred MIME name for that encoding, and must match the encoding given in the charset parameter of the Content-Type metadata of the external file, if any. [IANACHARSET]

Re your edit:

If I send a JS file to my friend, I hope he (she) can understand this JS file's character encoding from codes themselves when he (she) starts to browser or edit this JS file.

For that, you'll pretty much just have to tell him/her. If the file is in UTF-8 or Windows-1252 or ISO 8859-1, unfortunately there's no in-file indicator of the encoding available, so I'd include a comment at the beginning along the lines of:

// Encoding: UTF-8

If you're using UTF-16 or UTF-32, though, you should be able to tell your editor to use a BOM, which other editors should see and understand (if they're Unicode-aware editors). This would typically only apply if you were writing your comments in a text (language) requiring lots of multi-byte characters, and if you have a high ratio of comments to code (since the code is written with western text), although of course you're welcome to use any encoding you like. It's just that if the ratio of comments to code is low, you're probably better off sticking with UTF-8 even if the comments are in a text requiring lots of four-byte characters, because the code will only require one byte per character. (Whereas in UTF-16, you might have more two-byte instead of four-byte characters in your comments, but the code would always require two bytes per character; and in UTF-32, four bytes per character. So on the whole the file may well be larger even though the comments take less space. But here I'm probably telling you things you already know far better than I, if I'm guessing correctly about your reasons for the question.)

like image 161
T.J. Crowder Avatar answered Sep 28 '22 08:09

T.J. Crowder