Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify purpose of <script type="module"> + snippet #397

Merged
merged 4 commits into from
Dec 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion source/importing-css-assets-and-javascript/index.html.md.erb
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,15 @@ You can also use your own function to generate paths, for example if you're usin

## JavaScript

Before you import JavaScript from GOV.UK Frontend, you'll need to add the following to the top of the `<body class="govuk-template__body">` section of your page template (if you're not [using our Nunjucks macros](/use-nunjucks/)):
GOV.UK Frontend JavaScript must be run with `<script type="module">`.

This protects older browsers, including all versions of Internet Explorer, from running modern JavaScript that it does not support. Read about our [browser support](../browser-support/) for more information.

### Before you start

You'll need to add the following to the top of the `<body class="govuk-template__body">` section of your page template if you're not [using our Nunjucks macros](/use-nunjucks/).

This snippet adds the `.govuk-frontend-supported` class in supported browsers:

```html
<script>document.body.className += ' js-enabled' + ('noModule' in HTMLScriptElement.prototype ? ' govuk-frontend-supported' : '');</script>
Expand All @@ -182,7 +190,10 @@ Then import the JavaScript file before the closing `</body>` tag of your HTML pa

```html
<body class="govuk-template__body">
<script>document.body.className += ' js-enabled' + ('noModule' in HTMLScriptElement.prototype ? ' govuk-frontend-supported' : '');</script>

<!-- // ... -->

<script type="module" src="<YOUR-JAVASCRIPTS-FOLDER>/govuk-frontend.min.js"></script>
<script type="module">
import { initAll } from '<YOUR-JAVASCRIPTS-FOLDER>/govuk-frontend.min.js'
Expand Down