Floris
Floris

Reputation: 3127

Joomla add script from view to bottom of the head scripts

I would like to add this angular script:

<script src="/sitename/templates/templatename/app/modules/form/form.js"></script>

..to the bottom of the head scripts from the Joomla Nooku view my-account.html.php. Because in the template file there are the $doc->addScript()'s for adding scrips like AngularJS itself. So the custom script added in the view itself needs to be at the bottom.

How to do this?

If I use AddScript() in the view the script get added at the top of the head scripts.

I came up with a solution... well sort of. In the template file I specifiy the files that I would like to move to the bottom of the head scripts. Like this (a better solution/approach is welcome):

moveScriptToBottom($doc->_scripts, '/sitename/templates/templatename/app/modules/form/form.js');

function moveScriptToBottom(&$scripts, $src)
{
    foreach ($scripts as $key => $value) {
        if ($key === $src) {
            $move = $scripts[$key];
            unset($scripts[$key]);
            $scripts[$key] = $move;
        }
    }
}

Upvotes: 1

Views: 1748

Answers (3)

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13908

You can do that by using "addCustomTag", Though it won't guarantee that the script tag will be added to the end of the page, still it will solve a lot of sequence issues with Joomla.

$doc->addCustomTag('<script src="' . JURI::root(true) . '/js/yourscript.min.js" type="text/javascript"></script>');

Upvotes: 0

Francesco Abeni
Francesco Abeni

Reputation: 4265

There's no Joomla native way to do it, so the solution you came up with is more or less the only way to do it.

Upvotes: 1

Umair Ayub
Umair Ayub

Reputation: 21221

This will surely do it

<?php 
         //get the array containing all the script declarations
         $document = JFactory::getDocument(); 
         $headData = $document->getHeadData();
         $scripts = $headData['scripts'];

         //remove or add your script
         $scripts['/sitename/templates/templatename/app/modules/form/form.js']
         $headData['scripts'] = $scripts;
         $document->setHeadData($headData);
?>

Same way you can remove some un-wanted scripts by this

unset($scripts['/media/system/js/mootools-core.js']);

Upvotes: 1

Related Questions