This is baffling me, and am trying to understand the reason why. For some reason when JavaScript is embedded in an HTML5 file it uses UTF-8. However, if I link to an external HTML5 it no longer uses UTF-8. Here is what I have discovered:
I have an index.html file which uses <!DOCTYPE html>
. By default, because this is HTML 5 it defaults to UTF-8.
- WORKS: If I have unicode characters within my internal Javascript code then my Unicode characters show up fine.
- WORKS: If I have special unicode characters in the index.html document, and link to an external JavaScript file also containing unicode characters, the unicode characters show up fine.
- DOES NOT WORK: If I do NOT have special unicode characters in the index.html document, and link to an external JavaScript file containing unicode characters, the unicode characters do not show up show as expected. Instead they show up as some other cryptic characters.
So, Why does #2 work above, but not #3? I can get #3 to work by adding <meta charset="utf-8"/>
to the top of the index.html file. However, I am confused as to why I need this line if having is supposed to default to UTF-8 anyhow.
If the reason is because the default UTF-8 only applies to that file and not external files, then why does it work for #2?
PS. I have tried creating these files in both TextEdit and Xcode (on MacOS). In Xcode at least the default character encoding does seem to be set to UTF-8.