Importing jQuery into Joomla

允我心安 提交于 2019-11-26 15:29:42

This is the code we use to ensure only 1 copy of jQuery is imported. It simply checks to see if jQuery is already being imported and if not, then we import it :)

Joomla 2.5

<?php
  $app = JFactory::getApplication();
  if (!$app->get('jquery'))
  {
     $app->set('jquery', true);
     JFactory::getDocument()->addScript(JUri::root() . 'templates/template_name/js/jquery.js');
  }
?>

Joomla 3.x (no conflict mode):

JHtml::_('jquery.framework');

Joomla 3.x (normal mode):

JHtml::_('jquery.framework', false);

You need to insert this code into the index.php of your template, preferably near the top so you remember where it is. If you do not wish to override your template's index.php file, then you can also develop a small Plugin

Update:

As Bobby stated. A lot of extensions include their own copy of jQuery and a lot of them don't use this method and thus causes conflicts. All I know is that any good developer should know that multiple jQuery libraries causes conflicts and should use this code.

This is a great plugin.

http://extensions.joomla.org/extensions/core-enhancements/performance/jquery-scripts/18327

This plugin is meant to help clean and resolve front and back end issues when using instances of jQuery alongside the Mootools libraries.

WHAT IT DOES OUT-OF-THE BOX

  • calls jQuery and jQuery UI libraries from the Google CDN (with or without protocol) - but you can do it locally too,
  • places jQuery libraries after MooTools calls for perfect compatibility,
  • adds the noConflict() code alongside the jQuery library call,
  • strips out extra jQuery and jQuery UI libraries, including the noConflict() calls added by other modules or plugins,
  • lets you choose jQuery UI basic styling or custom theme.

WHAT YOU CAN TWEAK

  • disable MooTools libraries tentatively in the frontend,
  • enable or disable the plugin in specific portions of the site, from template to single page,
  • use reporting to get feedback on what the plugin engine has done,
  • add or remove scripts and stylesheets,
  • strip blank lines left by the modifications made to the page,
  • prevent some libraries to be stripped out,
  • modify the way the engine works by default (do not add or remove noConflict() code...),

Use Joomla! 3.0 — if you've spent that long trying you should help out with the Joomla! JavaScript Working Group which was built to address this.

In Joomla 3.x JApplication doesn't extend from JObject anymore which means when you want to use the same code in your extension for Joomla 2.5 and Joomla 3.x then you have to write the if condition like

if (!version_compare(JVERSION, '3', 'ge') && !JFactory::getApplication()->get('jquery', false)) {

Otherwise it will crash!! An example can be found here https://github.com/Digital-Peak/DPExtensions/blob/master/mod_dpslider/tmpl/default.php#L13

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