I tried the solution for this question, and while it works great if I want my script on every page: How to import jQuery as a global variable with Symfony's AssetMapper?
However, I have dozens of scripts and I don't want to ask the browser to load them on every page if I don't need them.
I have imported two packages via importmap:install; one which depends on jQuery as a global variable. These two packages are:
jqueryjquery-counterup
I have imported both of them and add both $ and jQuery as global variables on the window object inside a script that I import in the main assets/app.js file:
// assets/provide_jquery.js
import $ from 'jquery';
window.$ = window.jQuery = $;
// assets/app.js
import './provide_jquery.js';
import 'jquery.counterup';
Which works great. However, I usually don't want jquery-counterup loaded; it's only on very specific pages that I want it.
But if I import it with the asset() function inside a Twig template like this after the importmap('app') call:
<script src="{{ asset('vendor/jquery.counterup/jquery.counterup.index.js') }}"></script>
It will give me this error:
Uncaught ReferenceError: jQuery is not defined
Of course, once the page loads, console.log(jQuery) works because the global variable is now defined. So the jquery-counterup script appears to be loading before the global variables are declared.
The only way I've been able to get this to work is to use the defer attribute on the script or make it type="module" so it loads just before the DOMContentLoaded event but after global variable declaration.
And this works...but is it the best way? It feels like I'm stacking hacks on top of hacks to get this to work and there's something fundamental I'm missing.
Is there an easier/better way to add scripts to only specific pages?
One issue I can foresee is that including scripts this way means I don't get the preloading benefit the docs mention.