I’d like to inject some javascript into the before-script-load region.
Is it possible to achieve this via a theme, or theme-component?
The discussion revolves around injecting JavaScript into the before-script-load region in Discourse. gormus wants to add a script to this region, but is unsure if it’s possible via a theme or theme component. Lilly and Falco suggest that the order of execution may not be crucial, as the browser loads all head tag scripts regardless of their order. They recommend adding the script to the head tag area via the theme’s edit CSS/HTML section or a theme component.
However, gormus explains that the lack of control over the exact place where the script is injected is a problem. Specifically, they need to ensure that a dataLayer object is added to the page before any other script, including Google Tag Manager (GTM). pfaffman suggests using an initializer, referencing a meta topic about splitting up theme JavaScript into multiple files.
I’d like to inject some javascript into the before-script-load region.
Is it possible to achieve this via a theme, or theme-component?
does it need to run in that exact place (order of execution)? the browser will load all those head tag scripts regardless of their order. you can add the script in the head tag area by going to the edit CSS/HTML section of a theme in admin-customize-themes. if your theme is hosted and doesn’t allow customization, you can add it with a theme component (or to the head tag file of the repository if it’s your theme).
That is a development page that isn’t used in production.
As for the actual pages in Discourse, themes can inject content in the head element just fine, but without much control of the exact place where it happens, but as @Lilly said this shouldnt be an issue.
If you can tell us mor details about what exactly what you want to accomplish we may offer some suggestions.
I think you want to put it in an initializer.
Have a look at Split up theme Javascript into multiple files
But Falco knows lots more about that than I do.
Thank you @Lilly, @Falco and @pfaffman.
I believe this is my main problem.
As an example, I need to make sure the dataLayer object I set is always added to page before any other script, if possible. Especially before GTM loads (either via builtin, or a custom loader).
On my local development box, I tried utilizing the initializes, pre-initializers, and the head_tag.html template;
And inside head_tag.html template, I tried wrapping my code with <script></script> and the <script type="text/discourse-plugin" version="0.1"></script> tags.
With each one I can see the bootstrapping order relative to each other. But other than this, I don’t seem to have control over the order of the scripts loaded.