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?
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');
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).
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