Control order of loaded scripts

by antimatter   Last Updated January 11, 2018 17:10 PM

Unfortunatelly I can't register on the joomla forum, so I'll try my best here.
Please help, is there any way to control the order of loaded scripts.

Example: in my template's index.php I do:

$doc->addScript('my/script_a.js');

as the very first addScript(); So I load that script globally for all pages.

Then, in the default.php of my custom component I do:

$doc->addScript('my/script_b.js');

to add additional behaviour for that very component view specifically.

Logically I would assume that the addScripts in the index.php are added to the $doc object first and after that the addScripts in the component view are appended $doc object.
But what I end up with in the head is:

<script src="my/script_b.js"></script>
<script src="my/script_a.js"></script>

This bugs me pretty hard since my/script_a.js performes calculations my/script_b.js depends on, so the order is crucial.

Please, there must be a way to control the order of loading scripts otherwise this feature is pretty much pointless, isn't it?



Answers 1


  1. The JDocument's addScript method has no options for ordering (eg by priority or something like WP).
  2. There are numerous ways to solve your problem.

First, to understand why what you're doing is causing the problem you need to know the Joomla lifecycle.

  1. Bootstrap Framework & Application
  2. Route
  3. Component
  4. Modules
  5. Template
  6. Render and Respond

So when you call addScript in your template it gets added to the Document after the script added by your component.

Second, to the solutions...

  1. If the script loaded by your template has no dependencies then just write it inline above your

    <jdoc:include type="head" />
    
  2. Custom head tags are loaded after the scripts so in your component don't use addScript, use addCustomTag instead. eg.

    $doc->addCustomTag('<script src="my/script_b.js"></script>');
    
  3. Write a system plugin and in the onAfterRoute method first load your global script and then see if the option in the JInput is your component and then load your component script if it is (or just load it in your component tmpl as you're already doing).

  4. In the template get the head data from the JDocument and rustle it how ever you like.

Further reading:

https://github.com/joomla/joomla-cms/blob/staging/libraries/src/Document/HtmlDocument.php

jamesgarrett
jamesgarrett
January 11, 2018 22:12 PM

Related Questions


Load javascript script before </body> closing tag

Updated August 05, 2015 13:04 PM


addScript breaking frontend editing

Updated September 22, 2017 20:10 PM

How to set html5 property within template.php

Updated April 04, 2015 17:04 PM