Spomky-Labs / pwa-bundle

PHP library for generating a full featured PWA manifest
https://pwa.spomky-labs.com
MIT License
36 stars 2 forks source link

Allow javascript to be loaded at end of html #240

Open tacman opened 1 day ago

tacman commented 1 day ago

Description

Somewhere I read that the modern way to load javascript is at the html of the file, right before the closing body tag.

But when I tried to do that with the pwa() call being in the head (at the top, obviously), I ran into this:

image

I do not get that error when the js is in the top.

webpack encore used to have a defer setting, but assetmapper does not, which makes me think it's build it.

Example

This issue is not specific to my app, if you change base.html.twig in phpwa-demo, you'll see the same problem:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="This is a simple demonstration">
        <meta name="robots" content="all" />
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
        {% endblock %}
        {{ pwa(locale=app.request.locale) }}
    </head>
    <body>
    {% block content %}
        {% block body %}{% endblock %}
    {% endblock %}
    {% block javascripts %}
        {% block importmap %}{{ importmap('app') }}{% endblock %}
    {% endblock %}

    </body>
</html>
Spomky commented 23 hours ago

Hi @tacman,

Regarding the error "An import map is added after module script load was triggered" is caused by the position of the importmap call. It must be placed before any other <script> tag.

{% block javascripts %}
    {{ importmap('app') }}
{% endblock %}
{{ pwa() }}

The second error is caused by an import in your javascript file that is incorrect. You may have somthing like import from 'app'. This should be import from './app.js';

Somewhere I read that the modern way to load javascript is at the html of the file, right before the closing body tag.

This was the case few years ago. Now we have defer or async to tell the browser what to do with our scripts. You can set it using this syntax: {{ pwa(locale=app.request.locale, swAttributes={defer:'defer'}) }} (not tested)