If you are interested in indicating the file's encoding in a human-readable way, T.J. Crowder's idea (adding a comment to the file like // Encoding: UTF-8
) is just the thing. And as Jukka K. Korpela pointed out, you can use the BOM as well.
But if you want a machine-readable way to indicate charset that is declared in the document there are a couple of other ways:
For instance, on an Apache httpd server you might use any of the following declarations:
AddDefaultCharset UTF-8
AddCharset UTF-8 .js
AddType 'application/javascript; charset=UTF-8' js
*
* I am not interested in making the case for using "application/javascript"
over "text/javascript"
. But if you are interested in knowing why one or the other might be preferable, cf. https://stackoverflow.com/a/4101763/1070047. Given the topic, though, application/javascript
seems quite appropriate (especially if you are intending to use a BOM, because it indicates that the code should be treated as a binary).
If the code will be interpreted/processed/compiled server-side (e.g. PHP), you can set headers in the document, e.g.…
header("Content-Type: application/javascript; charset=utf-8");
At least within PHP, be sure to add that header statement before any output takes place.
Lastly, when determining which declaration to use, consider that (when understood/honored, i.e. not in IE) the BOM has greater authority than document headers. And both take precedence over the linked/sourced charset declarations (like <script type="application/javascript" src="script.js" charset="utf-8"></script>
).