Friday, February 12, 2016

Using Requirejs to load Jquery UI from a CDN

This post discusses how to use Require.js to load an external library.

One big benefit of Require.js is that it allows a developer to reliably load javascript modules without introducing dependency related conflicts. I needed to include Jquery UI into Plone 5 (which now manages the loading of javascript modules and dependencies using Require.js). If you're curious you can read more about use of Require.js in Plone.

In Plone 4.x you basically use the plain old javascript approach (with a bit of jquery magic) to load and run your scripts. Loading and using the Jquery UI datepicker might look like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
 $(document).ready(function(){
    $(function() {
    $( ".my-calendar-box" ).datepicker(
        { dateFormat: "dd/mm/yy" }
        );
  });
   
 });
</script>

With the introduction of Require.js in Plone 5 the code above would now look something like this:

<script>
require.config({
    "paths": {
      "jquery-ui": "//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min"
    }
});
require([ "jquery", "jquery-ui" ], function( $ ) {
       $(".my-calendar-box").datepicker(
        {
            dateFormat: "dd/mm/yy"
        }
        );
});
</script>

Note that when we define the path to "jquery-ui" the ".js" is removed from the end of the path. We can now call our newly defined "jquery-ui" module by using a require() call.
Plone 5 ships with some common modules such as jquery so we only need to  require "jquery".

If you want to get a list of all the javascript modules that Require.js has already loaded, run the following command on the javascript console of your Require.js powered app:
require.s.contexts._.defined

It is more common to put all your require.js related code in a separate ".js" file and then load that file. I have notes on doing something like that with SemanticUI.

No comments:

Sign up for my upcoming Plone 5 Book & Video tutorials

plone 5 for newbies book and videos