Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In HTML, script element has optional charset attribute.

What is the purpose of it?

When is it useful?

like image 897
Johnny Lim Avatar asked Apr 21 '12 09:04

Johnny Lim


People also ask

What does charset attribute do in HTML?

The charset attribute specifies the character encoding for the HTML document. The HTML5 specification encourages web developers to use the UTF-8 character set, which covers almost all of the characters and symbols in the world!

What is the purpose of charset?

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. It is not meant to override encoding information in HTTP headers, and it does not do that.

What is the purpose of the meta charset UTF-8 /> element in an HTML document?

In other words, <meta charset="utf-8"> tells the browser to use the utf-8 character encoding when translating machine code into human-readable text and vice versa to be displayed in the browser.

What is the use of script tag in HTML?

The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.


2 Answers

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.

For example, if the page is using Latin1, but the JS file was created with UTF-8.

like image 130
Oded Avatar answered Oct 04 '22 03:10

Oded


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. It is not meant to override encoding information in HTTP headers, and it does not do that.

This is useful when the author cannot control HTTP headers and the headers do not specify character encoding. 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.

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. If you use UTF-8 with a leading BOM, the BOM acts as a useful indicator that lets browsers infer the encoding. But it does not hurt to additionally use charset=utf-8.

like image 33
Jukka K. Korpela Avatar answered Oct 04 '22 04:10

Jukka K. Korpela