Add `defer` attribute to `<script>` tag
davidudo opened this issue · 1 comments
There is an issue of not being able to access elements by their ID in Storybook's route. This is because the DOM isn't completely loaded before the JavaScript gets executed. To resolve this, the defer
attribute needs to be added to the <script>
tags In the lib/phoenix_storybook/templates/layout/root.html.heex
and lib/phoenix_storybook/templates/layout/root_iframe.html.heex
files, so that the scripts only get executed after the DOM has been completely loaded.
In the lib/phoenix_storybook/templates/layout/root.html.heex
file, the following change should be made.
<%= if path = storybook_js_path(@conn) do %>
- <script phx-track-static type="text/javascript" src={application_static_path(path)}></script>
+ <script defer phx-track-static type="text/javascript" src={application_static_path(path)}></script>
<% end %>
- <script type="text/javascript" src={asset_path(@conn, "js/app.js")}></script>
+ <script defer type="text/javascript" src={asset_path(@conn, "js/app.js")}></script>
While in the lib/phoenix_storybook/templates/layout/root_iframe.html.heex
file, the following change should be made:
<%= if path = storybook_js_path(@conn) do %>
- <script nonce={csp_nonce(@conn, :script)} phx-track-static type="text/javascript" src={application_static_path(path)}>
+ <script defer nonce={csp_nonce(@conn, :script)} phx-track-static type="text/javascript" src={application_static_path(path)}>
</script>
<% end %>
- <script nonce={csp_nonce(@conn, :script)} type="text/javascript" src={asset_path(@conn, "js/iframe.js")}></script>
+ <script defer nonce={csp_nonce(@conn, :script)} type="text/javascript" src={asset_path(@conn, "js/iframe.js")}></script>
``
Hey David, using defer
can you be certain in which order the js file will be loaded?
Because the JS application file needs to be loaded before the storybook's JS file (the first one might declare hooks referenced in the second one)
JS loading used to be deferred, but we rolled back to synchronous loading: #268