问题
Is there any way to check in sfContext whether jQuery library is already added, using:
sfContext::getInstance()->getResponse()->addJavascript('/js/jquery-1.4.2.min.js');
or
addJavascript('jquery-1.4.2.min.js', sfView::getContext());
or
use_javascript('jquery-1.4.2.min.js');
in the templates?
Seems to me that adding more jQuery's stops their action.
回答1:
You should use your own check.
- Use your own
sfWebResponse
- Override
addJavascript
- Add the check
So create a new myWebResponse.class.php
file in /lib/response/
folder (create it), with this code :
class myWebResponse extends sfWebResponse
{
public function addJavascript($file, $position = '', $options = array())
{
$this->validatePosition($position);
// check if the file to add is jquery
// nb: you might update the regex
if (preg_match('/jquery/i', $file))
{
// retrieve all loaded js
$files = array_keys($this->getJavascripts());
// check if one them containt jquery
// nb: you might update the regex
$isJquery = preg_grep("/jquery/i", $files);
// jquery found so do not add the file
if ( ! empty($isJquery))
{
return;
}
}
$this->javascripts[$position][$file] = $options;
}
Then, use your new response by default. In your apps/frontend/config/factories.yml
, add:
all:
response:
class: myWebResponse
You're done.
来源:https://stackoverflow.com/questions/10813920/symfony-check-whether-jquery-already-included