DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones Build AI Agents That Are Ready for Production
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
Build AI Agents That Are Ready for Production

Just dropped: New 2026 “Cloud-Native Foundations” Trend Report. See how teams are tackling complexity, cost & reliability.

AI can investigate. Engineers still decide. See how both work together across incident response in this DZone + Datadog webinar on Oct. 29.

Related

  • Generic and Dynamic API: MuleSoft
  • Microservices With .NET Core: Building Scalable and Resilient Applications
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation

Trending

  • Building a Practical Cloud-Native Golden Path: A Guide to Kubernetes-Based Service Delivery, Self-Service, and Developer-Friendly Defaults
  • MCP Is the USB-C of AI — Here's What That Actually Means for Your Architecture
  • RavenDB Launches Quill to Bring Production AI Agents to Enterprise SQL Systems, No Migration Required
  • YAML vs XML vs JSON: History, Trade-offs, and Where Each Wins in the Age of Agentic AI
  1. DZone
  2. Coding
  3. JavaScript
  4. Exploring Intercooler.js: Simplify AJAX With HTML Attributes

Exploring Intercooler.js: Simplify AJAX With HTML Attributes

Discover how Intercooler.js makes AJAX simple using HTML attributes, no heavy JavaScript needed. A smart and lightweight alternative for dynamic pages.

By 
Nagappan Subramanian user avatar
Nagappan Subramanian
DZone Core CORE ·
May. 21, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.2K Views

Join the DZone community and get the full member experience.

Join For Free

Intercooler.js is a lightweight JavaScript library that enables developers to add AJAX functionality to their web applications with minimal effort. Inspired by HTML's simplicity, it allows the use of HTML attributes to handle dynamic updates instead of writing extensive JavaScript code. This library is ideal for developers who want the power of AJAX without diving into complex frameworks like React or Angular.

Note: While Intercooler.js is still supported, its successor, htmx, offers additional features and enhanced browser capabilities.

Why Choose Intercooler.js?

  • Ease of Use: Fetching dynamic content and updating an HTML element can be as simple as adding the ic-get-from attribute to an element.
  • Lightweight: At around 15KB, Intercooler.js ensures your web app remains fast and responsive.
  • Framework-Free: It integrates seamlessly into existing projects without relying on external frameworks.
  • HTML-Enhanced: It extends HTML semantics using attributes like ic-get-from, ic-post-to, and ic-trigger-on, transforming static HTML into dynamic, interactive interfaces.

Key Features of Intercooler.js

  • Simplified AJAX Requests: Use ic-get-from and ic-post-to attributes to fetch or send data.
  • Partial Page Updates: Refresh specific parts of the web page without reloading the whole page.
  • Event Binding: Trigger updates based on user interactions like clicks or mouseovers via ic-trigger-on.
  • Declarative UI: Focus on clean HTML while Intercooler.js handles JavaScript logic behind the scenes.

Getting Started

1. Download Intercooler.js

Start by visiting the official https://intercoolerjs.org/ website or a trusted CDN repository. You can either download the library or use a CDN link.

2. Include Intercooler.js in Your HTML

HTML
 


Alternatively, if you downloaded the file, include it like this:

HTML
 


3. Add the Required Dependency:

Intercooler.js depends on jQuery, so ensure jQuery is included before Intercooler.js:

HTML
 


4. Set Up Your HTML Structure

Here's a simple example to demonstrate how Intercooler.js works:

HTML
 






    Intercooler.js Setup

    

    





    

Welcome to Intercooler.js


Setup: Here, we have to import both jQuery (a required dependency for Intercooler.js) and the Intercooler.js library using app.get('/weather', async (req, res) => { const start = parseInt(req.query.start) || 0; const limit = parseInt(req.query.limit) || 10; const response = await axios.get(API_URL); let html = ''; for (let i = start; i < start + limit; i++) { html += `${response.data.hourly.time[i]} ${response.data.hourly.temperature_2m[i]} ${response.data.hourly.relative_humidity_2m[i]} ${response.data.hourly.wind_speed_10m[i]}`; } res.send(html); }); }


How It Works

  1. The user's coordinates are captured (lat, long) using the browser's navigator.geolocation

  2. When the page loads, the first 10 rows of weather data are fetched from the /weather endpoint.

  3. When the last row of the table comes into view (ic-trigger-on="scrolled-into-view"), more rows are fetched dynamically.

  4. Based on the start and limit query parameters, the backend slices the data and appends rows until the dataset is exhausted.


Example 4: Understanding Intercooler.js Events

In this example, we explore how Intercooler.js events like ic-beforeSend, ic-success, and ic-error can be utilized to enhance form interactions with dynamic visual and functional feedback.

ic-beforeSend Event:

  • Displays a loading spinner and disables the submit button while an AJAX request is being processed.

  • Ensures a smooth user experience during data submission.

ic-success Event:

  • Restores the button to its original state after successful submission.

  • Updates a target area (#responseMessage) with a success message dynamically received from the server.

ic-error Event:

  • Handles errors gracefully by restoring the button state and displaying error messages from the server.

Dynamic API Response:

  • The server simulates different outcomes (success, failure, error) based on user input, allowing for versatile testing of event behaviors.

Event listeners ensure smooth interaction and graceful error handling:

JavaScript
 
document.addEventListener('ic-beforeSend', function (e) {

  const button = e.target.querySelector('button[type="submit"]');

  button.dataset.originalContent = button.innerHTML;

  button.innerHTML = ` Loading...`;

  button.disabled = true;

});



document.addEventListener('ic-success', function (e) {

  const button = e.target.querySelector('button[type="submit"]');

  button.innerHTML = button.dataset.originalContent;

  button.disabled = false;

  document.getElementById('responseMessage').innerHTML = `
${e.detail.response}
`; });


Server Logic: The API dynamically responds based on user input,


JavaScript
 
app.post('/mock-api', (req, res) => {

  const { input } = req.body;

  if (input === 'success') {

    return res.status(200).send('Success! Data was processed correctly.');

  } else if (input === 'failure') {

    return res.status(400).send('Failure! Invalid input provided.');

  } else {

    return res.status(500).send('Error! Something went wrong.');

  }

});


How It Works

  1. The user submits a form, triggering an ic-beforeSend event to show a loading spinner.

  2. On server response:

    • Success: Displays a success message dynamically.

    • Failure/Error: Reverts the button and displays error feedback.

Example 5: Polling with Intercooler.js

In this example, we explore how to implement Polling using Intercooler.js to dynamically fetch weather updates at regular intervals without requiring user interaction. This real-time data fetching is both efficient and user-friendly.

Automatic Data Refresh:

  • The ic-poll="2s" attribute sets up polling every 2 seconds, ensuring the latest weather data is fetched automatically.

  • The ic-src="/poll_example" specifies the endpoint providing the updated weather information.

Trigger on Page Load:

  • The polling mechanism begins immediately when the page loads using ic-trigger-on="load", eliminating the need for manual initiation.

Geolocation Support:

  • Uses the browser's navigator.geolocation to capture the user's latitude and longitude.

  • Updates the ic-get-from URL dynamically to fetch data for the user's location.

Loading Indicator:

  • Shows a spinning icon () while data is being fetched.

Backend Integration:

  • The server fetches real-time weather data from the Open-Meteo API to simulate real-time updates for the polling mechanism.

Polling Element in HTML: The element with ic-poll automatically triggers requests to fetch weather data every 2 seconds:


HTML
 


  Loading weather data...


The server fetches weather data and randomly selects a weather record to display:

JavaScript
 
app.get('/poll_example', async (req, res) => {

const response = await axios.get(`${BASE_API_URL}?latitude=${lat}& longitude=${long}¤t_weather=true`);

    const data = response.data.current_weather;

    if (!data) {

      throw new Error('Weather data unavailable');

    }



const weatherData = {

time: new Date().toLocaleTimeString(),

      temperature: data.temperature,

      humidity: data.relative_humidity || 'N/A',

      windSpeed: data.windspeed || 'N/A',

};

res.send(`



  Time: ${weatherData.time} 
Temperature: ${weatherData.temperature}°C
Humidity: ${weatherData.humidity}%
Wind Speed: ${weatherData.windSpeed} km/h
`); });


How It Works:

Initial Data Load:

  • When the page loads, the user's location is captured, or a default location is used.

  • The backend serves weather data for the specified latitude and longitude.

Real-Time Polling:

  • Intercooler.js repeatedly calls the /poll_example endpoint every 2 seconds (ic-poll="2s") to fetch fresh weather updates.

Frontend Updates:

  • The weather details (Time, Temperature, etc.) are dynamically updated in the container without requiring a page refresh.

Complete code example is available in github.

Conclusion

If we are developing simple web application project with few server interaction of server updates or use some external apis to store or fetch the data (like google apis), Intercooler.js would be best choice to integrate it easily.

AJAX API HTML HTTPS JavaScript Visual Studio Code Attribute (computing) Data (computing) Event Form (document)

Opinions expressed by DZone contributors are their own.

Related

  • Generic and Dynamic API: MuleSoft
  • Microservices With .NET Core: Building Scalable and Resilient Applications
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook