# Element “script” must not have attribute “charset” unless attribute “src” is also specified.

> Canonical HTML version: https://rocketvalidator.com/html-validation/element-script-must-not-have-attribute-charset-unless-attribute-src-is-also-specified
> Attribution: Rocket Validator (https://rocketvalidator.com)
> License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

The `charset` attribute on the `<script>` element tells the browser what character encoding to use when interpreting the referenced external script file. When a script is written directly inside the HTML document (an inline script), the script's character encoding is inherently the same as the document's encoding — there is no separate file to decode. Because of this, the HTML specification requires that `charset` only appear on `<script>` elements that also have a `src` attribute pointing to an external file.

Including `charset` without `src` violates the HTML specification and signals a misunderstanding of how character encoding works for inline scripts. Validators flag this because browsers ignore the `charset` attribute on inline scripts, which means it has no effect and could mislead developers into thinking they've set the encoding when they haven't.

It's also worth noting that the `charset` attribute on `<script>` is **deprecated** in the HTML living standard, even for external scripts. The modern best practice is to serve external script files with the correct `Content-Type` HTTP header (e.g., `Content-Type: application/javascript; charset=utf-8`) or to simply ensure all your files use UTF-8 encoding, which is the default. If you're working with an older codebase that still uses `charset`, consider removing it entirely and relying on UTF-8 throughout.

## Examples

### Incorrect: `charset` on an inline script

This triggers the validation error because `charset` is specified without a corresponding `src` attribute.

```html
<script charset="utf-8">
  console.log("Hello, world!");
</script>
```

### Correct: Remove `charset` from inline scripts

Since inline scripts use the document's encoding, simply remove the `charset` attribute.

```html
<script>
  console.log("Hello, world!");
</script>
```

### Correct: Use `charset` with an external script (deprecated but valid)

If you need to specify the encoding of an external script, both `charset` and `src` must be present. Note that this usage, while valid, is deprecated.

```html
<script src="app.js" charset="utf-8"></script>
```

### Recommended: External script without `charset`

The preferred modern approach is to omit `charset` entirely and ensure the server delivers the file with the correct encoding header, or simply use UTF-8 for everything.

```html
<script src="app.js"></script>
```
