CakePHP 2 $this->Html->script order

岁酱吖の 提交于 2019-12-06 03:42:48

问题


I am trying to insert JS files into the view but they are being inserted in the wrong order.

In my default.ctp I have this

$this->Html->script(array(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
    'global'
), array('inline'=>false));

echo $this->fetch('script');

In my view I have this:

$this->Html->script('jquery.fancybox.pack', array('inline' => false));

But when I view the source it comes out like this:

<script type="text/javascript" src="/js/jquery.fancybox.pack.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/global.js">

Which is obviously the wrong order so the jQuery plugin is not working.

What am I doing wrong?


回答1:


Generally, I echo out the required scripts in the layout (instead of adding them to the buffer) and then script block (buffered scripts) after. This ensures that scripts required for each view are echoed first. Your default.ctp would look something like this instead:

// get echoed immediately
echo $this->Html->script(array(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
    'global'
));
// everything else from the view, echoed after
echo $this->fetch('script');

Or, you can specify a special block for your preceding scripts.

echo $this->Html->script(array(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
    'global'
), array('block' => 'firstScripts');
echo $this->fetch('css');
echo $this->fetch('firstScripts');
echo $this->fetch('script');



回答2:


Not sure how much time you invested in building your current system, but you can try using a hierarchical resource loader helper, instead of standard cakePHP one.

Standard resource loader unfortunately has no way to deal with dependencies between different files and just loads them in the order you provide them (view is parsed before layout).




回答3:


Use this at head section.

Html->script('jquery-1.11.1.js') ?>
fetch('script') ?>


来源:https://stackoverflow.com/questions/9904372/cakephp-2-this-html-script-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!