user3305818 user3305818 - 7 months ago 18
Javascript Question

How to restrict to load same js multiple times

I am talking about the CakePHP Helper. I want to load the JS files using the helper of CakePHP.

Consider that the construction of the Helper class will load all necessary JS files.

But, I need to call that Helper in a single view multiple times. So, it's possible that the JS files will be called multiple times. I want to load those JS files only once.

Can anyone help me to cover this?

This will be my Helper script

<?php
App::uses('AppHelper', 'View/Helper');

/**
* @alias Mathjax Class for helper
* @description This class is to define helper in cakephp.
*/
class MathjaxHelper extends AppHelper {

/*
* Constructor of the class.
*/
function __construct(View $View, $settings = array()) {
parent::__construct($View, $settings);
//login to load all necessary JS files.
}

function create() {
//this function will return the helper html
}

}

Answer

Use HtmlHelper::script

If you use HtmlHelper::script method, with 'inline' => false, to load the js files they will by default be included once.

Layout file

To use this method, ensure that in the layout file the $scripts_for_layout variable is echoed out. E.g.:

<html>
    <head>
        ...
    </head>
    <body>
        ...

        <?php echo $scripts_for_layout ?>
    </body> 
</html>

View files

In your views, elements or helpers - simply ensure the script method is called using the inline parameter:

<?php $this->Html->script('my', array('inline' => false)); ?>

In this way it doesn't matter how often you call the script method with a given js file - it will appear in the resultant html output only once.