1

How can a script loaded as an ES module be reinitiated after changes are made in Live Preview? In my experience a script loaded as a module is executed the first time Live Preview is opened, but then isn’t executed on subsequent loads as the page refreshes with edited content.

According to this article, modules will only execute once per page. I’m including a function that is executed on the window’s load event and it is fired each time Live Preview is updated — which makes me think the script should be loaded and executed each time Live Preview updates.

Here's a simplified case. Include a script that alerts some text when the script is loaded and on the window’s load event.

alert('Script Loaded')

window.addEventListener('load', () => {
    alert('Window Loaded')
})

Include it in the page as a module:

<script type="module" src="app.js"></script>

Open Live Preview and the alerts fire. Make a change, page refreshes, content is updated — no alerts.

Include it as a regular script

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

Open Live Preview and the alerts fire. Make a change, page refreshes, content is updated — alerts fire again.

I’m working around it by loading a legacy nomodule version of the script in Live Preview, but curious if there is another solution or event to listen for to trigger the JS to execute again when Live Preview is updated.

{#
 # Load legacy JS in Live Preview because modules
 # aren’t executed after the page reloads
/#}
{% if craft.app.request.isLivePreview %}
    <script src="app.js"></script>
{% else %}
    <script type="module" src="app.js"></script>
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.