How to Add Lodash to HTML Using a CDN
This guide explains how to integrate the Lodash utility library into an HTML document using a Content Delivery Network (CDN). By linking to a hosted version of Lodash, you can immediately access its utility functions without downloading local files or configuring build tools like Webpack or Vite. Below are the steps to select a CDN provider, embed the script tag, and verify that the library works in your project.
Step 1: Select a CDN Provider
Lodash is hosted on several major public CDNs. The most common providers are jsDelivr, cdnjs, and unpkg. You can choose any of the following URLs:
- jsDelivr:
https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js - cdnjs:
https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js - unpkg:
https://unpkg.com/lodash@4.17.21/lodash.min.js
Using the minified version (.min.js) is recommended for
faster load times and reduced bandwidth.
Step 2: Insert the Script Tag
Add a standard <script> tag to your HTML document
containing the src attribute set to your chosen CDN
link.
For optimal performance and to ensure the DOM is ready before
execution, place the script tag inside the <body>
element, just before the closing </body> tag.
Alternatively, you can place it inside the <head>
section.
Step 3: Complete HTML Example
Below is a complete HTML template demonstrating how to load Lodash via CDN and use its functions:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lodash CDN Example</title>
</head>
<body>
<h1>Testing Lodash CDN</h1>
<!-- 1. Load Lodash from CDN -->
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<!-- 2. Use Lodash in your custom script -->
<script>
// Check if Lodash is loaded
const numbers = [10, 5, 100, 2, 1000];
const minNumber = _.min(numbers);
console.log("Lodash Version:", _.VERSION);
console.log("Minimum Number:", minNumber);
</script>
</body>
</html>Step 4: Verify the Installation
To confirm Lodash has loaded properly:
- Open the HTML file in any modern web browser.
- Open the browser's Developer Tools (press
F12or right-click and select Inspect). - Navigate to the Console tab.
- Type
_and press Enter. If Lodash is properly loaded, the console will output the Lodash library function object. Any custom script using the_prefix will now execute without errors.