Google's CDN in Zend Framework

880 Views Asked by At

How can I get Google's CDN with fallback working in Zend Framework(Zend_View)?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">!window.jQuery && document.write('<script src="/base/js/jquery-1.7.2.js"></script>');</script>

Thanks for your help.

3

There are 3 best solutions below

1
On BEST ANSWER

The way you wrote is correct.

I just added 2 things.
1) Base URL
2) Unescaping the special chars

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
!window.jQuery && document.write(unescape('%3Cscript src="<?php echo $this->baseUrl(); ?>/base/js/jquery-1.7.2.js"%3E%3C/script%3E'));
</script>

For using head script view helper

 $java_script_code= '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>';
    $java_script_code.= '<script>';
    $java_script_code.= '!window.jQuery && document.write(unescape(\'%3Cscript src="' . $this->baseUrl() . '/base/js/jquery-1.7.2.js"%3E%3C/script%3E\'));';
    $java_script_code.= '</script>';

You can do in view this

$this->headScript()->appendScript($java_script_code);

or in controller (update base url above)

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

FYI: Head Script Helper

0
On

Create a file fallback.js under /base/js/ directory and paste following

!window.jQuery && document.write('<script src="/base/js/jquery-1.7.2.js">

Add following code in you bootstrap.php

protected function initJquery() {
    $this->bootstrap('view');
    $view = $this->getResource('view'); //get the view object

    //default loads from google CDN
    $view ->jQuery()->enable()->setVersion('1.7');

    $view ->headScript()->prependFile($view->baseUrl().'/base/js/fallback.js');
    return $view;
}

I hope it helps

0
On

Best practice is to be made as @Venu said, using the headScript().

If you have customized or will modify the base where is your files you can use the setBaseUrl() that will modify the path where it does include the files.

//File: /public/js/jquery.js
$view->baseUrl("js/jquery.js");