简体   繁体   中英

Where is the best place to put the custom jquery and javascript in Zend Framework?

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 ?

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.

  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM