paul
paul

Reputation: 13516

How to organise multiple portlets which require jQuery and jQuery extensions?

I am developing a few portlets for Liferay 6.2 and chose to use jQuery along with a number of extensions.

I seem to be getting problems where the extensions I need are attaching themselves to a jQuery instance which is not the one that I am using in the portlet. So when I come to use an extension it is not available.

My code looks something like this. The liferay-portlet.xml contains

    <header-portlet-javascript>/js/jquery-1.12.2.min.js</header-portlet-javascript>
    <header-portlet-javascript>/js/jquery-ui.min.js</header-portlet-javascript>
    <header-portlet-javascript>/js/datepicker-de.js</header-portlet-javascript>
    <header-portlet-javascript>/js/calendar.js</header-portlet-javascript>

In the JSP

<script type="text/javascript">
var $CAL; 
jQuery.noConflict();
jQuery( document ).ready(function( $ ) {
    $CAL = jQuery; // create my own jQuery handle

    ...

    $CAL.datepicker.setDefaults($CAL.datepicker.regional['de']);
    // $CAL.datepicker is NULL !
});
</script>

I'm not sure, but I think the datepicker function gets attached to a different jQuery instance. The debugger lists about 7 instances of jQuery and 3 instances of jQueryUI that different portlets are loading.

After some research, we tried to load all JS libraries in the theme but some portlets are loaded before the theme. Our current attempt is to load them in a 'hook'. That is still on-going.

At the moment we are creating all the portlets ourselves. It is possible that in the future we might want to use a 3rd party portlet so I'm wondering what the best approach is.

EDIT

The answer below and How to resolve two jquery conflict? show how to avoid the conflict when multiple jQuerys are loaded. Is this best practice in Liferay portlet development? I assume that the are times when requiring different jQuery versions is unavoidable but is it normal for each portlet to simple load its' own copy of jQuery?

Upvotes: 1

Views: 402

Answers (1)

guest271314
guest271314

Reputation: 1

$CAL = jQueryis the issue. Define $CAL as variable referencing jQuery.noConflict()

Create a different alias instead of jQuery to use in the rest of the script.

var j = jQuery.noConflict();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<script type="text/javascript">
  $CAL = jQuery.noConflict();
  $CAL(document).ready(function() {
    $CAL.datepicker.setDefaults($CAL.datepicker.regional['de']);
    
    console.log("jQuery version ", $CAL().jquery);
    $CAL("body").datepicker("dialog", "10/14/2016");
  });
</script>

Upvotes: 1

Related Questions