0
votes

where is the best place to put the jquery and javascript scripts in zend framework?

shall i put every script in js file and append in the controller like :

$this->view->headScript()->appendScript

or to leave in the phtml page as is ?

2

2 Answers

2
votes

I'd say it depends on your scripts, if your script is linked to your controller, you could include it in the _init() method of your controller.

I usually prefer to include my .js scripts inside my view (when they concern only one unique view) using $this->jQuery()->addOnload() for jQuery and:

<?php $this->headScript()->appendFile('/js/user-list.js') ?>
<?php $this->headScript()->captureStart() ?>
site = {
    baseUrl: "<?php echo $this->baseUrl() ?>"
};
<?php $this->headScript()->captureEnd() ?>

for js scripts. As you can see in this second example, a real advantage to use captureStart() is that you can use PHP to generate contents in your Javascript. It can be pretty useful for translating a word for example.

Finally, _initView() method in your bootstrap is a good place to put web-site relative .js.

1
votes
  • Javascript you need for the entire site you want to add during bootstrap, in a view setup or initView method.
  • Javascript you need for some controller, you should append in the init() method of that controller.
  • Javascript you only need for a certain action, you should append in that action.

This way the client never has to download more data/files than really needed.