Intercooler in a Nutshell

Intercooler is very simple to use if you have any web development experience. Anyone reading this should be familiar with anchor tags in HTML:

  <a href="http://intercoolerjs.org/">Get Intercooler</a>

This tells a browser:

"When a user clicks on this link, issue an HTTP GET request to 'http://intercoolerjs.org/' and load the response content into this browser window".

Intercooler builds on this simple concept:

  <a ic-post-to="/button_click">Click Me!</a>

This tells a browser:

"When a user clicks on this link, issue an HTTP POST request to '/button_click' and load the response content into this element".

So you can see that it is very similar a standard anchor link, except that:

  • A different HTTP action is used
  • The request is done via AJAX
  • The response replaces the contents of the element, rather than the entire page

And there you have the core of intercooler. It's a simple idea, but you will be surprised how much you can do with it.

Here is a working version of this example:

Click Me!

The beauty of intercooler is that it allows you to develop web applications in much the same way that they have always been developed, leveraging tools and techniques that have been honed over a decades experience, while incrementally adding AJAX to the highest value areas of your web applications. This allows you to preserve your complexity budget (you have a complexity budget, right?) much later into your project, so you can see exactly where the application needs something fancy.

Additionally, this makes intercooler a great tool for adding AJAX incrementally to an existing web app: there is no need for a huge rewrite, you can just start using it in the high value parts of your app quickly and simply.

Installing Intercooler

Intercooler is just another javascript library. You can download and install the latest version from the release page.

Intercooler can be loaded off of NPM based CDNs, such as https://unpkg.com/intercooler.

If you are using Bower, the package name for Intercooler is intercooler-js.

Intercooler depends on JQuery, version 1.10.0 or higher, and is compatible with JQuery 1, 2 and 3.

The Core Intercooler Attributes

The core attributes of intercooler are: ic-get-from, ic-post-to, ic-put-to, ic-patch-to and ic-delete-from.

Each of these attributes takes a (typically server-relative) URL to issue a request to and then issue an HTTP GET, POST, PUT, PATCH or DELETE respectively, when the element they are declared on is triggered (see below) and then loads the content of the response into the element.

Underlying all these attributes is the ic-src attribute, which can be thought of as the same as ic-get-from, but with no event trigger. (It can be triggered manually or via dependencies, see below.) The attributes above are defined in terms of ic-src, you will not find a need to use this attribute directly very often.

Here is an example button that issues a PUT:

  <button ic-put-to="/put_demo">Put Me!</button>

Note: if you wish to use the data-* prefix for intercooler attributes, you can add the following meta tag to your head section:

<meta name="intercoolerjs:use-data-prefix" content="true"/>

Triggering Intercooler Requests

The core intercooler attributes specify where to make a request, but they don't specify when to do so. By default intercooler will use the "natural" event for an element:

  • For form elements, issue the request on the submit event.
  • For elements matching the JQuery :input pseudo-selector except buttons, issue the request on the change event.
  • For all other elements, including buttons, issue the request on the click event.

If you wish to listen for an event on another element in the DOM, or the document or window object, you can use the ic-trigger-from attribute.

For any element you can override the event that triggers an intercooler response by using the ic-trigger-on attribute:

  <a ic-post-to="/mouse_entered" ic-trigger-on="mouseenter">Mouse Over Me!</a>

Mouse Over Me!

If you wish to trigger an intercooler request only when an event has occurred and the value of an element has changed, you can use the changed modifier as well:

    <input type="text" name="text" ic-post-to="/text_changed" ic-trigger-on="keyup changed"
               ic-target="#text-div" placeholder="Enter Some Text"/>
    <div id="text-div"></div>
  

If you wish for an event to only trigger a request once (e.g. a click to load a detail div) you can use the once modifier:

    <div ic-get-from="/details" ic-trigger-on="click once"/>
          Click for Details...
    </div>
        

Finally, you can add a delay to the request by using the ic-trigger-delay attribute:

    <input type="text" name="text" ic-post-to="/trigger_delay" ic-trigger-on="keyup changed"
               ic-target="#text-div2" ic-trigger-delay="500ms" placeholder="Enter Some Text"/>
    <div id="text-div2"></div>
  

This attribute allows you to wait until a given interval of time has passed before issuing the request. If the event occurs again, the timer will reset and begin waiting again. This is useful, for example, if you want to issue a request when a user pauses in a text input.

Special Events

In addition to the standard JQuery events , Intercooler supports a special event: scrolled-into-view, which is fired when an element is scrolled into view.

This can be useful for implementing UI patterns such as infinite scroll or lazy image loading.

Targeting Other Elements

Sometimes you don't want to replace the content of the element that causes an intercooler request, but rather some other element on the page. For example, you may have a link that, when it is clicked, should replace an entire section of content with the server response.

For these situations you can use the ic-target attribute, which takes a JQuery selector (typically with an element id).

  <a ic-post-to="/target_span" ic-target='#target_span'>Click Me!</a>
  <span id="target_span">You haven't clicked the link next to me...</span>

Click Me! You haven't clicked the link next to me...

Forms & Input Values

Including form data is very simple in intercooler. By default, any element causing an intercooler request will include the serialized version of the nearest parent form. So if the element is a form or is nested within a form the entire form will be serialized and sent up with the request.

Intercooler includes some additional parameters in the request to help you understand which element invoked the request, see Anatomy of an Intercooler Request below for more information.

Including Other Values In Requests

Sometimes you may want to include the values of inputs in a different part of the DOM. To do this, intercooler supports an attribute, ic-include, in which you can specify a JQuery selector to indicate what other elements to serialize in the request or you can specify a JSON object of name/value pairs to include in the request.

Submit the form above...

You can also include values stored persistently in the localStorage object by using the ic-local-vars attribute, which takes a comma separated list of keys to include in the request. (You can set localStorage values using the X-IC-Set-Local-Vars header, mentioned below.)

File Uploads

File uploads can be accomplished with intercooler by adding the enctype='multipart/form-data' to a form that is set up to submit via intercooler. When intercooler detects this, it will use the FormData object for creating the request, which will include any file inputs.

Note that FormData is only available as of IE10. Also be aware that sub-elements within the form that trigger their own AJAX requests (e.g. an input that triggers on change) will not be submitted as multipart/form-data requests, and will therefore not include any files.

Polling

A common pattern in web development is to have a page poll a URL for updates. Until the day comes when push technologies are available widely, this technique is the best way to dynamically update a UI without a specific client-side event happening.

Intercooler supports an attribute, ic-poll, which tells an element to poll whatever URL is associated with it on a given interval. This attribute can be of the form "10s" or "100ms", where "s" indicates seconds and "ms" indicates milliseconds.

Below is an example:

          <span ic-poll="2s" ic-src="/poll_example">
            This span will poll the server every two seconds...
          </span>
        

Note that if you want the polling element to load data immediately after the page renders, you can add the attribute ic-trigger-on="load"

This span will poll the server every two seconds...

Configuring Polling Behavior

Intercooler supports a few ways to modify polling behavior. The first is the ic-poll-repeats attribute, which you can use to limit the number of times a intercooler will poll for a given element.

The second is the ic-pause-polling attribute, can be set to true to tell an element not to poll.

A third way is to use the X-IC-CancelPolling response header, which will cancel polling of an element. See the Anatomy of an Intercooler Response section for more details on intercooler response headers.

You can resume polling after it has been cancelled by issuing the X-IC-ResumePolling response header.

Note that both of the headers will propogate to the nearest ic-poll element that is a parent of the current target.

Using these two tags and headers, it is fairly simple to set up a "Pause/Play" UI for a pol-based live view.

If you wish to pause polling when a window is hidden or is not focused, you can use the ic-disable-when-doc-hidden or ic-disable-when-doc-inactive attributes, respectively.

Progress Indicators

An important but often overlooked aspect of UI design is indicating when a remote request is in flight. Modern browsers have unfortunately made the situation worse for normal web requests by making the request indicator less and less obvious, for what I can only assume are aesthetic considerations.

AJAX requests have never had a proper indicator mechanism, so it is up to us to build one. Intercooler provides tools to make this easy.

The ic-indicator Attribute

The first tool available is the ic-indicator attribute, which specifies a selector of an indicator element in the DOM. This element will be made visible during the life of the intercooler request, and hidden afterwards.

Here is an example:

          <button ic-post-to="/indicator_demo" ic-indicator="#demo-spinner">Click Me!</button>
          <i id="demo-spinner" class="fa fa-spinner fa-spin" style="display:none"></i>
        

This attribute can be specified on a parent element if you want a group of elements to share the same indicator.

The ic-indicator Class

Another option is to use the ic-indicator class on an element that is a child of the element issuing the intercooler request.

Here is an example:

          <button ic-post-to="/indicator_demo2">Click Me!
            <i class="ic-indicator fa fa-spinner fa-spin" style="display:none"></i>
          </button>
        

This is less code and is better UX for some situations, but has the disadvantage that if the parent element is replaced the indicator will be removed, causing what can appear to be an abrupt transition.

CSS-Based Indicators

If you wish to use CSS to style your progress indicator transitions, rather than the default show/hide logic, you can use the ic-use-transition class. See the ic-indicator documentation for more details and an example.

Disabling Elements

By default, intercooler will apply the disabled class to the element that triggers an intercooler request. This can be used to give a visual hint to the user that they should not click or otherwise trigger the request again, and is Bootstrap-friendly.

In the above demos you will see that the button greys out during the request, which is due to Bootstrap's handling of this CSS class.

The ic-global-indicator Attribute

The ic-global-indicator attribute is similar to the ic-indicator attribute, but will be shown in addition to any local indicators. This can be used to implement a site-wide progress indicator.

CSS Element Transitions

As of the 0.9.0 release, Intercooler allows you to use CSS 3 transitions to animate content swaps. It does this by adding the ic-transitioning class to the target element that is about to be swapped, waiting a moment, doing the swap, and then removing the ic-transitioning class from the target.

The amount of time between when the ic-transitioning class is added, the swap is done and then the ic-transitioning class is removed is determined as follows

Time to swap is determined by:

  • If the attribute ic-transition-duration is defined on either the target or triggering element or parents thereof, use the time defined by that attribute.
  • Otherwise, add the transition-duration and transition-delay defined in CSS for the element using 0 if either is absent.

Intercooler then waits an additional 5 milliseconds before removing the ic-transitioning class.

This process lets you define CSS transitions for your elements. Here is a simple example that fades the button out and then back in:

  <style>
    #transition-1 {
      transition: all .9s;
    }

    #transition-1.ic-transitioning {
      opacity: 0;
    }
  </style>
  
Click Me!

Since we are using CSS, we can transition elements within the swapped content, rather than the entire content. In this example we only fade in and out the content in the button. Note that we need to define the ic-transition-duration to let intercooler know how long to wait, since the transition delay is not defined on the target.

Note that the CSS transition time is set to a slightly smaller amount than the ic-transition-duration is, to avoid timing issues with the ic-transitioning class removal.

  <style>
    #transition-2 span {
      transition: all .9s;
    }

    #transition-2.ic-transitioning span {
      opacity: 0;
    }
  </style>
  
Click Me!

And, to show that you can use any CSS transition, here is the same example that uses font size:

  <style>
    #transition-3 span {
      transition: all 900ms;
    }

    #transition-3.ic-transitioning span {
      font-size: 4px;
    }
  </style>
  
Click Me!

Using CSS transitions gives you very fine-grained controll over the look and feel of your Intercooler-based app, and they are fun to play with. (Just don't overdo it.)

Client-Side Tools

Intercooler is primarily a library for making AJAX calls, but it does provide some simple but powerful tools for doing client-side DOM manipulation, allowing you to implement many client-side needs using only a few attributes:

Ready Handling

A common pattern in jQuery-based applications is to have a ready handler that executes once the page is loaded, and that often is used to hook up event handlers or to initialize javascript widgets:

    $(document).ready(function() {
      $("#my-element").click(function() { doSomethingOnClick() });
    });
  

Intercooler has a similar mechanism so that you can wire event handlers (or use javascript plugins) to partial content that has been swapped into the DOM:

    Intercooler.ready(function(rootContent) {
      rootContent.find("#my-element").click(function() { doSomethingOnClick() });
    });
  

Note that rather than doing a global lookup of elements, you do a look up from the root element of the swap, which is passed in as an argument to the callback. This helps you avoid accidentally adding multiple handlers to the same element.

Adding & Removing Classes After A Delay

In order to fine tune transitions or provide other visual easements in your app, you may find yourself wanting to add or remove classes to an element after a specified delay. Intercooler provides two attributes, ic-add-class and ic-remove-class to do this.

In this example, we apply a toRed class to the text inside the button after a click:

Click Me!

Timed Removal Of Elements

A common pattern in AJAX applications is to "flash" an element after a request: show the element for a bit then remove it from the DOM. Intercooler includes the ic-remove-after attribute for this situation which, like ic-poll, can take the form "2s" or "1500ms". Once the given amount of time has elapsed, the element will be removed from the DOM.

This can be paired with the ic-add-class or ic-remove-class to achieve a smooth effect.

Here is an example, where the message is faded out before being removed:

Click Me!

Client-Side Actions

Sometimes it is useful to have a purely-client side action in response to a given action trigger. A good example is if you wish simply to remove a element when another element is clicked, without a server request. Intercooler provides the ic-action attribute for this situation.

The full details of the syntax for this attribute are available on the detail page for it, but here are a few examples:

   <a ic-action="fadeOut;remove">Fade Then Remove Me!</a>
        
  <a ic-action="slideToggle" ic-target="#chesterton-quote">Toggle Chesterton!</a>
        
Toggle Chesterton!

Switch Class

Sometimes you may want to switch a class between siblings in a DOM without replacing the HTML. A common situation where this comes up is in tabbed UIs, where the target is within the tabbed UI, but the tabs themselves are not replaced.

Intercooler has an attribute, ic-switch-class that enabled this pattern. It is placed on the parent element and the value is the name of the class that will be switched to the element causing the intercooler request.

Below is an example of a tabbed UI using this technique. Note that the tabs are not replaced, but the active class is switched between them as they are clicked.

        <ul class="nav nav-tabs" ic-target="#content" ic-switch-class="active">
          <li class="active"><a ic-get-from="/tab1">Tab1</a></li>
          <li><a ic-get-from="/tab2">Tab2</a></li>
          <li><a ic-get-from="/tab3">Tab3</a></li>
        </ul>
        <div id="content">
          Pick a tab
        </div>
        
Tab 1
  <a ic-action="slideToggle" ic-target="#chesterton-quote">Toggle Chesterton!</a>
        
Toggle Chesterton!

History Support

Intercooler provides simple history support for AJAX calls. This functionality is currently experimental, but is usable and unlikely to change dramatically going forward.

If you want an intercooler call to push its target URL into the location bar and create a history element, simply add the ic-push-url attribute to the element and ensure that the target of the element has a stable HTML id.

Here is an example:

    <a id="hist-link" ic-post-to="/history_demo" ic-push-url="true">Click Me!</a>
  
Click Me!

When Intercooler makes a request to /history_demo it snapshots the HTML of the target before swapping in the new content and saves this snapshot to local storage. It then does the swap and pushes a new location onto the history stack.

When a user hits the back button, Intercooler will retrieve the old content from storage and swap it back into the target, simulating "going back" to the previous state.

Specifying History Snapshot Element

If you use history extensively within your app, you will want to use a stable element for snapshotting HTML so that if a user is many pages deep in a click stream and goes back multiple steps, the element that will be restored into is still available on the screen. There is typically a div that wraps the main content of your application and this is the suggested element to mark as the element to snapshot and restore to, using the ic-history-elt attribute

It is highly recommended that you set this attribute in your intercooler application if you are using history.

Including Request Paramters In The URL

Somtimes you may want to include one or more request parameters in the URL that is set in the navigation bar. You can do this by using the ic-push-params attribute, which lets you specify which parameters should be included in the URL. A common place where this might be useful is in search dialogs, where you want the search term to appear in the URL so it can be copied and pasted or refreshed and retain the search information.

Conditionally Updating The Location/History

Sometimes whether or not you want to update the location of the page will be dependent on the result of the intercooler request. In that case, rather than using the ic-push-url attribute, you can use the X-IC-PushURL header, outlined below in the Intercooler Response section.

Note: This is one area where intercooler leverages some relatively recent web technologies that may not be present on older browsers. Namely, it uses Web Storage and the JSON object, both of which are not available in various older browsers. If you wish to maintain maximum compatibility with your intercooler website, you should not use the history support.

Progressive Enhancement

Intercooler provides a mechanism for progressive enhancement. The ic-enhance attribute can be set to true on an element, all child anchor tags and form tags will be converted to their equivalent intercooler implementations.

Anchor tags (links) will be converted to ic-get-from with ic-push-url set to true.

Forms will be converted to the intercooler equivalent action (e.g. a POST form will convert to ic-post-to)

Commonly you will have an ic-target set up at the top level of your DOM, paired with a ic-enhance attribute. You can differentiate on the server side between normal and AJAX requests by looking for the intercooler headers.

Here is an example:

    <div ic-enhance="true">
      <a href="/enhancement_example">Click Me!</a>
    </div>
  

Server Sent Events BETA

Server Sent Events are an HTML5 technology allowing for a server to push content to an HTML client. They are simpler than WebSockets but are unidirectional, allowing a server to send push content to a browser only.

Browser support for Server Sent Events is widespread, and there are polyfills available for browsers that do not support them natively.

Intercooler supports Server Sent Events with the ic-sse-src attribute. This tells intercooler to establish a Server Sent Event connection with the given URL and listen for both messages and events.

    <div ic-sse-src="/sse_endpoint">A Server-Sent Event Element</div>
  

Server Sent Event Sources

The simplest way to use Server Sent Events is via messages. Server Sent Messages will simply have the content of the message swapped in as the body of the target that the attribute is on. This can be used as an alternative to the more common client-side polling behavior.

If you wish to append or prepend, rather than replace the content, you can use the ic-swap-style attribute to specify so.

Server Sent Event Triggers

Another technique with Server Side Events is to use events (rather than messages) to trigger a request, rather than replace content directly. This can be done by specifying a Server Side Event source with the ic-sse-src tag on a parent element, and then specifying the Server Side Event that triggers a given child using the special sse: prefix.

  <div ic-sse-src="/sse_endpoint">
    <span ic-trigger-on="sse:contact_updated" ic-src="/contact/1"></span>
  </div>
         

For the HTML above, the span HTML will be updated from the /contact/1 URL when a Server Side Event of the name contact_updated is fired.

Note: Server Sent Events are relatively new and are a beta feature of both intercooler and the web in general. They should be used with caution.

Anatomy Of An Intercooler Request

Intercooler requests are fairly straight forward HTTP requests, but they do have a few non-standard aspects that help you out.

Special Parameters

In addition to the form serialization discussed above, intercooler requests include a few additional parameters in every AJAX request:

Parameters

Parameter Description
ic-request This will always be true for intercooler requests.
_method Because not all browsers support PUT and DELETE requests in AJAX, intercooler uses the Rails convention and adds a _method parameter to the request whose value will be the HTTP Method type (e.g. DELETE).
ic-element-id The HTML id of the element that caused the request, that is the element that has the ic-post-to or similar attribute on it.
ic-element-name The HTML name of the element that caused the request, that is the element that has the ic-post-to or similar attribute on it.
ic-target-id The ID of the target element of the request. This can be used to figure out which bit of partial HTML to render, if a given URL is used to target different areas depending on the context.
ic-trigger-id The ID of the target that initially triggered the request. This can be different than the element that caused the request: it could be a child element.
ic-trigger-name The HTML name of the target that initially triggered the request. This can be different than the element that caused the request: it could be a child element.
ic-current-url The current URL of the page.
ic-prompt-value The user input from the javascript prompt if the ic-prompt attribute is used

Headers

Header Description
X-IC-Request Set to true
X-HTTP-Method-Override Set to the HTTP Method type (e.g. DELETE) for the request, to communicate the actual request type to the server if it cannot be directly supported by the client.

Anatomy Of An Intercooler Response

Intercooler responses are HTML fragments. Here is an example of some content:

  <div>
    Here Is Some Content!
  <div>
      

This would be swapped in as the body of the element that initiated the request.

The returned content can, of course, contain Intercooler attributes itself, which will be all wired up.

No-Op Responses

Intercooler interprets an empty body or a single whitespace character in a request as a No-Op, and will do nothing in response. If you want to replace an element with only whitespace, return at least two whitespaces worth of content.

Intercooler Response Headers

Not all UI needs can be captured via pure element swapping. Occasionally you may need to invoke a client side event, let other elements know to refresh themselves, redirect the user entirely, and so on.

To handle these situations, intercooler supports custom HTTP headers. These headers can be used to instruct intercooler to perform additional work in addition to swapping in the returned HTML.

Here is a table of the response headers intercooler supports:

Header Description
X-IC-Trigger Allows you to trigger a JQuery event handler on the client side. The value of this header can either be a plain string for the event name, or a JSON object that satisfies the jQuery parseJSon() requirements, where each property is an event name to trigger, and the value of each property is an array of arguments to pass to that event.
X-IC-Refresh A comma separated list of dependency paths to refresh.
X-IC-Redirect Causes a client-side redirect to the given URL.
X-IC-Script Allows you to evaluate arbitrary javascript.
X-IC-CancelPolling Cancels any polling associated with the target element or parent thereof.
X-IC-ResumePolling Restarts any polling associated with the target element or parent thereof.
X-IC-SetPollInterval Sets the polling interval to the given value for the target element or parent thereof.
X-IC-Open Opens a new window at the given location.
X-IC-PushURL Sets a new location for the page and saves the history of the element being replaced.
X-IC-Remove Removes the target element. The value of this header can either be true in which case the element is removed immediately or a numeric time delay (e.g. 750ms or 2s) in which case it will be removed after the given amount of time. If there is a delay the ic-removing class will be added to the element, allowing for a CSS3 animation to be applied prior to the elements removal.
X-IC-Title Sets the title of the page/document to the given header value. Please note that only ASCII characters are guaranteed to work.
X-IC-Title-Encoded The same as X-IC-Title but the value is expected to be URI encoded
X-IC-Title-Encoded URI decodes the given header value and sets the title of the page/document to the decoded value. Use this header if you need to show UTF-8 characters in the title.
X-IC-Set-Local-Vars A JSON object that will be used to set values in the client side localStorage object. Can be used in conjunction with the ic-local-vars attribute to maintain client-side state across requests.

Dependencies In Intercooler

Intercooler has a novel mechanism for managing inter-element dependencies which builds on the concept of REST-ful URLs.

Intercooler uses server path relationships to encode dependencies. The idea is straight forward and natural if you have are familiar with REST-ful URL schemas:

If an element reads its value (i.e. issues a GET) from a given server path, and an action updates that path (i.e. issues a POST to it), refresh the element after the action occurs.

So, as a simple example, consider this button and div:


  <button ic-post-to="/example/path">A Button</button>

  <div ic-src="/example/path">A Div</div>
     

Here the div depends on the button, because they share a path with one another. When Intercooler issues a POST to the given path (on a user click), upon completion, it will issue a GET to the same path, and replace the div with the new content, if it is different.

What Paths Depend On What?

It's all very simple when the POST and GET are to the same path, but what if they aren't? What if the post is to /jobs/2341/start and the get is from /jobs/2341? Or vice-versa?

Our answer is as follows:

Two server paths express a dependency if either path is the starting path of the other.

So:

Path Updated Path Read Dependency?
/foo /bar NO
/foo /foo YES
/foo/bar /foo YES
/foo /foo/bar YES
/foo/doh /foo/bar NO

Explicit Dependencies

The dependencies above are managed implicitly by Intercooler and, with reasonable layout of your restful URLs, should handle many cases. However, there may be times when you need to express dependencies explicitly. In Intercooler, you can use the ic-deps attribute to express additional paths that an element depends on.

To disable dependencies on an element, you can use ic-deps="ignore"

Intercooler Events

Intercooler fires JQuery-style events that can be listened for. Here is a table of the events that are fired:

Event Description
log.ic(evt, msg, level, elt) Event fired when log messages occur internally in intercooler (can be used to debug specific DOM elements.)
beforeAjaxSend.ic(evt, ajaxSetting, elt) Fired on the document before every AJAX request, allowing you to modify the settings object (e.g. to add or remove parameter or headers, change content types, etc.) You can cancel the request by setting the cancel property of the ajaxSettings object to true.
beforeHeaders.ic(evt, elt, xhr) Triggered before intercooler headers are processed.
afterHeaders.ic(evt, elt, xhr) Triggered after intercooler headers are processed.
beforeSend.ic(evt, elt, data, settings, xhr, requestId) Triggered before sending an intercooler AJAX request to the server.
success.ic(evt, elt, data, textStatus, xhr, requestId) Triggered after a successful intercooler request is received
after.success.ic(evt, elt, data, textStatus, xhr, requestId) After headers are processed and the swapping mechanism has begun
error.ic(evt, elt, status, str, xhr) Triggered after an error occurs during an intercooler request
complete.ic(evt, elt, data, status, xhr, requestId) Triggered after an intercooler request completes, regardless of status. This event is triggered on the body tag.
onPoll.ic(evt, elt) Triggered before a poll request is dispatched
handle.onpopstate.ic(evt) Triggered when intercooler handles an onpopstate event. Triggered on the document body.
elementAdded.ic(evt) Triggered on an element when it is processed by intercooler.
pushUrl.ic(evt, target, data) Triggered when a URL is pushed
beforeHistorySnapshot.ic(evt, target) Triggered before a snapshot is taken for history. Can be used to unwire javascript-based widgets that have messed the DOM up after insert.

Example

Here is some code that uses the BlockUI library to block the UI when an intercooler request is in flight:

        $(function(){
          $('#blocking-button').on('beforeSend.ic', function(){
            $.blockUI();
          }).on('complete.ic', function(){
            $.unblockUI();
          });
        })
      

Event Attributes

Javascript can also be invoked with the following attributes: ic-on-beforeSend, ic-on-success, ic-on-error, and ic-on-complete.

Here is the same demo as above using attributes rather than a JQuery event handler:

These attributes can be placed on parent elements if you want to specify a behavior for an entire secion of a DOM tree.

Server-Side Techniques

A great strength of Intercooler is that it is inherently server-side technology agnostic: you can use anything you'd like to serve up the partial HTML and headers needed for your Intercooler-based front-end to function. That being said, there are some techniques that can be applied across all server-side technologies to help you build a better, cleaner web application:

Check for the ic-request parameter

You can use the ic-request parameter to decide if a request has originated from intercooler (and, therefore, demands a partial bit of HTML) or from a top level browser. If you are using the ic-push-url attribute to enable AJAX-based history and navigation this can be especially useful.

Check the ic-target-id parameter

If you have an even more advanced user interface, you may find yourself making requests to the same URL for different parts of the screen (this is common if you have a second-level navigation within a page) and you will want to differentiate between requests that are targeting different parts of the UI. Intercooler provides the ID of the target element, if it exists, in the ic-target-id parameter

Use the ic-trigger-id to determine who triggered a request

If it is annoying to set up multiple routes with your server-side technology, you may have a few actions that you want to run through a POST to a single URL. You can differentiate between the elements that are sending these posts up by giving them IDS and then checking the ic-trigger-id parameter.

Keep your templates DRY

Intercooler works best with a tidy server-side, with refactored and well composed templates that generate both the full and partial HTML necessary for a web app.

Leverage multiple HTTP Actions at the same URL

Intercooler makes it easy to issue more exotic HTTP actions, like DELETE and PUT. Depending on your server-side technology, you can use this to minimize the URL surface area of your app and adhere to REST-ful URL design. There is no reason to limit this concept to only JSON APIs: it often leads to a minimal and tidy code base when used judiciously for partial HTML.

Fire client-side events to manage UI state that can't be handled with content swaps

Not every UI pattern is amenable to HTML content swapping. For example, you may want to use a modal popup from a framework like Bootstrap. In situations like these, you can often use the IC-Trigger attribute to signal from the server-side to the client-side that something happened, and write javascript to update the UI accordingly (e.g. hide a modal after an update.)

This is a powerful technique for minimizing the coupling and complexity of your application while still retaining the full power of a javascript client side environment.

Error Handling & Debugging

Intercooler offers a few tools for handling errors. The most important one is the ic-post-errors-to attribute, which will post all AJAX and client side errors that occur during content swaps to a given URL. This is an invaluable way to understand what is going on on the client side of your web application.

There is also the ic-on-error attribute, which allows you to specify an expression to evaluate when an AJAX error occurs.

Finally, there are the error events specified above that allow you to handle more specific error situations if you wish.

Integrated Client-Side Debugger

Intercooler comes with an integrated client-side debugger. You can launch the debugger by including the following script on your page:

<script>
  $.getScript("https://intercoolerreleases-leaddynocom.netdna-ssl.com/intercooler-debugger.js");
</script>

The debugger consists of three tabs: "Elements", "Logs" and "Errors".

"Elements" has a clickable list of active elements on the page. When you click on one of the items in the list, it will be highlighted on the page, and intercooler-related details will be shown about it.

"Logs" has the intercooler log stream, including clickable links to the elements that caused each message.

"Errors" will show any errors that intercooler detects (e.g. bad targets on an element).

You can launch the debugger on this page by clicking this button:

If you would like, you can capture the intercooler log event if you want to see the low level events that are driving intercooler:

        $(function(){
          $(window).on('log.ic', function(evt, msg, level, elt){
            console.log(msg);
          });
        })
  

Using Intercooler from Javascript

Intercooler does not have a large javascript API because it is intended to sit in the background, issuing and processing requests. Events and dependencies can be used to handle almost all dynamic situations that intercooler is appropriate for.

There are, however, a few methods you can invoke on the global Intercooler object:

Method Description
Intercooler.refresh(eltOrPath) If the argument is an element, it will issue a new AJAX request. If it is a string path, it will issue a request for all dependent elements.
Intercooler.triggerRequest(elt, handler) Triggers an intercooler request for the given element. An optional handler can be used to handle processing the response, which can be useful for integrating with third party libraries that work with JSON. See the Twitter Typeahead Example
Intercooler.processNodes(elt) This will wire in all intercooler behavior to the given element and its children. Useful if you've done an out of band content swap.
Intercooler.closestAttrValue(elt, attr) Finds the value of the given attribute that is closest in the parent hierarchy of the given element, including the element. Null if none is found.
Intercooler.verbFor(elt) Finds the associated HTTP verb for the element.
Intercooler.isDependent(elt1, elt2) Returns true if elt2 depends on elt1
Intercooler.getTarget(elt1) Returns the target of the given element.
Intercooler.processHeaders(elt, xhr) Parses an XHR response for Intercooler headers and executes them on a given DOM element. This can be useful for integrating with third party libraries that issue their own Ajax requests.
Intercooler.ready(func(elt)) Takes a function that takes a single argument, elt, to be run on the top level of all content that is swapped into the DOM by intercooler. This is the Intercooler equivalent of the jQuery ready concept.
LeadDyno.startPolling(elt) Begins polling for the given element
LeadDyno.stopPolling(elt) Stops polling for the given element

Javascript Expression Evaluation

Intercooler evaluates expressions for attributes (ic-on-beforeSend, ic-on-success, ic-on-error, and ic-on-complete) and passed in via headers, etc. in a somewhat complex way:

If the expression is a single symbol, it will be looked up in the global namespace as a function and then, if it exists, it will be called with the given arguments.

If not, the expression will be evaluated in a new scope.

This allows sites with security restrictions around the use of eval() to still make use of scripting within intercooler.

Also note that, because expressions are evaluated in a new scope, if you are using an attribute that supports a return value (e.g. ic-on-beforeSend returning false to cancel a request) you must return the value using an explicit return statement.

Cross-Domain AJAX

Below are some basic guidelines for getting cross-domain AJAX requests working with Intercooler. For an authoritative resource on cross-domain HTTP requests refer to the MDN CORS documentation.

Response Headers

For responses to cross-domain requests you will need to set the Access-Control-Allow-Origin header to the domain which will be making requests. For example:

          res.header('Access-Control-Allow-Origin', 'http://example.com');
        

And if you want to use any of the Intercooler response headers you will need to set the Access-Control-Expose-Headers to include the headers you want to use. For example:

          res.header('Access-Control-Expose-Headers', 'X-IC-Trigger, X-IC-Script');
        

Cross-Domain Credentials (Cookies and HTTP Auth)

If you want to send cookies with cross-domain AJAX requests you'll need to set the Access-Control-Allow-Credentials header to true on the server. For example:

          res.header("Access-Control-Allow-Credentials", "true");
        

And also set withCredentials to true on the xhrFields property of the AJAX settings in the browser. For example:

          $(document).on("beforeAjaxSend.ic", function (evt, settings) {
              settings.xhrFields = {withCredentials: true};
          });
        

For more information on cross-domain AJAX requests and credentials refer to the MDN XHR documentation.

Preflighted OPTIONS Requests

Based on the MDN documentation on preflighted requests, a request is preflighted if:

  • It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
  • It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

To avoid preflighted OPTIONS requests for Intercooler requests you can do the following:

          $(document).on("beforeAjaxSend.ic", function (evt, settings) {
              delete settings.headers['X-IC-Request'];
              delete settings.headers['X-HTTP-Method-Override'];
          });
        

Of course, this means that you won't have access to these headers on the server.

jQuery and Cross-Domain AJAX

Based on the jQuery AJAX settings documentation, the following additional points should be noted about cross-domain AJAX:

  • Synchronous operations are not supported.
  • The error handler is not called.

zepto.js Compatibility

zepto.js is a minimalist, largely jQuery-compatible API for use with modern browsers, that is focused on staying small (<10kB when gzipped, compared with 32kB for the latest versions of jQuery) while providing most of the familiar jQuery APIs.

As of version 1.1.0, intercooler offers zepto.js compatibility in place of jQuery. To use zepto, rather than jQuery:

Using zepto with intercooler.js brings the entire support payload for an intercooler-based web application down to 18kB, which compares favorably with many JS frameworks (Vue.js, the smallest by a long shot, comes in at 23kB)

Differences with jQuery + intercooler.js

There are a few differences in behavior when using zepto.js with intercooler:

  • Local HTML fragments (e.g. ic-get-from="#some_div" will not work)
  • Event namespacing is reversed and uses a colon separator, so the beforeSend.ic event becomes the ic:beforeSend event.
  • zepto does not serialize non-form elements, so ic-include must point to a form if you wish to include a value from an input. The JSON form is not affected.

Philosophy

It can be easy for some developers to dismiss intercooler as overly simple and an archaic way of building web applications. This is intellectually lazy.

Intercooler is a tool for returning to the original network architecture of the web. Using HTML as the data transport in communication with a server is what enables HATEOAS, the core distinguishing feature of that network architecture. Intercooler goes with the grain of the web, rather than forcing a more traditional thick-client model onto it, thereby avoiding the complexity and security issues that come along with that model.

Yes, intercooler is simple, but it is a deceptive simplicity, very much like the early web.

A few related blog posts for the interested reader:

On Churn

Many javascript projects are updated at a dizzying pace. Intercooler is not.

This is not because it is dead, but rather because it is (mostly) right: the basic idea is right, and the implementation at least right enough.

This means there will not be constant activity and churn on the project, but rather a stewardship relationship: the main goal now is to not screw it up. The documentation will be improved, tests will be added, small new delarative features will be added around the edges, but there will be no massive rewrite or constant updating. This is in contrast with the software industry in general and the front end world in particular, which has comical levels of churn.

Intercooler is a sturdy, reliable tool for web development.

Conclusion

And that's it!

Not a ton to it, which is kind of the point: you can build surprisingly rich UIs with this simple and easy to understand tool, and you can do it incrementally in the areas that matter the most for your users.

"There is no need to be complex..."