alphagov / govuk-prototype-kit

Rapidly create HTML prototypes of GOV.UK services
https://prototype-kit.service.gov.uk
MIT License
301 stars 236 forks source link

Plugin scripts with `"type": "module"` run too late #2353

Closed colinrotherham closed 11 months ago

colinrotherham commented 11 months ago

Description of the issue

Prototypes using window.GOVUKFrontend will break when https://github.com/alphagov/govuk-frontend/pull/4264 is released

Why? Plugin scripts configured with "type": "module" execute after prototype JavaScript has already run

Steps to reproduce the issue

  1. Install the GOV.UK Frontend v5 preview (via GitHub commit)

    npm install --save "alphagov/govuk-frontend#5b2bfde4f"
  2. Edit prototype app/assets/javascripts/application.js and add:

    console.log(window.GOVUKFrontend)
  3. Open the prototype in a browser

Actual vs expected behaviour

Actual: GOV.UK Frontend global window.GOVUKFrontend is undefined Expected: Prototype scripts are also deferred, ensuring window.GOVUKFrontend is available

Prototypes correctly using window.GOVUKPrototypeKit.documentReady() are unaffected

colinrotherham commented 11 months ago

Not strictly a bug since since impact depends on:

  1. How many prototypes access window.GOVUKFrontend directly?
  2. How many plugins (or future plugins) access window.GOVUKFrontend directly?
  3. How widely is window.GOVUKPrototypeKit.documentReady() used to initialise safely?
colinrotherham commented 11 months ago

The simplest fix was to add type="module" to application.js in: