Use RequireJS to auto-load the Search Bubble

Over the last two posts (here and here) I’ve been creating my search bubbble with an intent to componentize my work. It’s a really simple example – just a search icon on a header bar and a pop-up bubble. The intent is to learn the techniques that I can apply in bigger projects. In this article on the subject I’m going to integrate RequireJS to auto-load my components and libraries.

I will note here that it isn’t worth the trouble in this size project. I’ve got a pretty good reuseable component for the search bubble from the last article. I’m loading jQuery and Bootstrap from the CDN. What could possibly need more infrastructure? Well, I’m glad you asked. One component doesn’t seem worth it. Let’s say that navigation bar was a component and it included icons that could be loaded to the left and right, and each of them relied on other components. Now, those components maybe relied on Javascript libraries that you downloaded from the Internet. And those libraries relied on other libraries as well. Now you have a whole nested tree of dependencies several layers thick.

What order do you load the various Javascript files in? How slow is your page load going to be now?

In reality, you want to load just the libraries for the components you are going to be using, you want those libraries to be defined as dependencies and you want them loaded only at the point in time you need them. Enter RequireJS – an Asynchronous Module Definition (AMD) API for Javascript Modules. If you follow some fairly basic rules, this makes it easy for you to write modules that are aware of their dependencies and handles all the messy loading stuff for you.

Let’s take a look at the new index.html file I created right at the beginning:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>My Test Page</title>
    <link rel="stylesheet" href="">
    <link href="css/site.css" rel="stylesheet">
            <li id="nav-search"><span class="glyphicon glyphicon-search"></span></li>
    <script src="js/lib/require.js" data-main="js/init"></script>

Not much has changed. I’ve organized things a little – the CSS is being loaded from a specific CSS directory and the JavaScript is being loaded from a JS directory. Let’s take a look at that JS directory:


In my js directory I have two other directories. js/components is where I’ll put my code. The only thing in js/lib is require.js – you can download this from the RequireJS web site. Notice the data-main element in my code? This is “bootstrapping” – use require.js, but then load this other piece of code that tells RequireJS how to get your application started. There are two parts to the js/init.js file. The first is configuration for RequireJS:

  baseUrl: 'js',
  paths: {
    'jquery':   '',
  shim: {
    'bootstrap': { deps : [ 'jquery' ]}

The baseUrl element tells RequireJS where to find our Javascript files. If I didn’t have the baseUrl then we would have to tell every single component the explicit path. Everything is relative to my js directory. Next, I have to tell RequireJS where my libraries are. In this case, I’m loading the libraries from the CDN. jQuery is aware of RequireJS but only if we refer to it as jquery. Similarly, I don’t want to be referring to Bootstrap with it’s full URL – let’s just call it something simple. My final shim section tells RequireJS that bootstrap is dependent on jquery. In general, you only need to do this for libraries downloaded from the Internet.

My original Javascript had some initialization code to create the search box object. That application initialization code goes next:

requirejs(['jquery', 'components/searchbox', 'bootstrap'], function($, searchbox) {
  $(document).ready(function() {
    var s = new searchbox('#nav-search');

Let’s take a look at this a little bit. The function call has two components – an array of things this code depends on, then the function to call when all the requirements have been satisfied.
The elements of the array become variables to my function, allowing me to encapsulate the entire functionality into a module.

Remember the Namespace I created to hold the component class? That is no longer needed because of this encapsulation.

Once all those three libraries are loaded the function will be called. This function registers an event handler for when the document is ready and then instantiates the search box code.

I’vealready done most of the work in the js/components/searchbox.js, but let’s take a look at the basic form of a “class-style” AMD module:

define(['jquery', 'components/utils'], function($, utils) {
    return function Searchbox(id) {
        // My class goes here
        return {
            // My public interface goes here

I’m bringing in a non-class-style module called utils – I’ll put the createDIV() and generateGUID() functions there. For now, all I need to do is include the searchbox class from my prior post:

define(['jquery', 'components/utils'], function($, utils) {
  return function Searchbox(id) {
    var clickId     = id,
        searchBoxId = utils.generateGUID();
    var clickHandler = function(evt) {
      var elem = $(evt.currentTarget),
        srch = $('#' +;
      // Find out how many search boxes there are
      //   -> More than 1, then destroy them
      if (srch.length > 0) {
      // Compute the size and position relative to what was clicked
      var left   = elem.position().left - 24,
        top    = elem.position().top + elem.height() + 16,
        width  = 300,
        height = 50;
      // If there are no search boxes, then fall through
      // to here and create one.
      var srch = utils.createDIV(searchBoxId, 'bubble', left, top, width, height);  
      srch.html("<div class='search'><input type='text' name='search' placeholder='Search'></div>");
    $(clickId).css({ 'cursor': 'pointer'})
      .click({ id: searchBoxId }, clickHandler);
    // Public Interface
    return {
      getID: function() { 
        return clickId; 
      getSearchBox: function() {
        var s = $('#'+searchBoxId);
        return (s.length > 0) ? s : null;

So that’s the class-style module. What about a non-class-style module? One that’s just a collection of functions I want to use? In the searchbox.js file, I’m depending on components/utils and I use utils.createDIV() and utils.generateGUID(). The only thing I need to do is encapsulate these functions in an object. In the class-style module, I return a function – the constructor of the class. In the collection-of-functions, I return an object that has all the functions listed in it. In the searchbox.js file I’m bringing in components/utils, so place this code in js/components/utils.js:

define(['jquery'], function($) {
  return {
    createDIV: function(id, cssClass, left, top, width) {
      return $("<div id='" + id + "' class='" + cssClass + "'></div>")
          'display': 'block',
          'position': 'absolute',
          'left': left + 'px',
          'top': top + 'px',
          'width': width + 'px'
    generateGUID: function() {
      var d = new Date().getTime(),
        guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = (d + Math.random() * 16) % 16 | 0;
          d = Math.floor(d / 16);
          return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);

      return guid;

Can I go further with this? Absolutely. I can, for example, move the header HTML code into a component and add that as a component. That header component can include other components and so on. Now I can modularize the code in such a way that it is just a blank body element and a require.js call. Everything is done on the client and in Javascript. Of course, that’s an extreme case, but you can see the possibilities there.