How to add jQuery from a CDN?

Adding jQuery to a web page from a Content Delivery Network (CDN) is a common practice because it allows you to use the speed and reliability of a third-party server.

Choose a jQuery CDN

Select a CDN provider that hosts jQuery. Common choices include Google, Microsoft, and jQuery's official CDN. For this example, we'll use the Google CDN.

Include jQuery in Your HTML

In the <head> section of your HTML document, add a <script> tag with the CDN URL.

<!DOCTYPE html> <html> <head> <title>My Web Page</title> <!-- Include jQuery from the Google CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <!-- Your web page content here --> </body> </html>

Specify the jQuery Version

In the src attribute of the <script> tag, you can specify the version of jQuery you want to use. In the example above, we've used version 3.5.1. You can replace this version number with the one you need.

Use jQuery in Your JavaScript

After including jQuery, you can start using it in your JavaScript code. Here's a simple example of selecting an element and performing an action:

<!DOCTYPE html> <html> <head> <title>My Web Page</title> <!-- Include jQuery from the Google CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <button id="myButton">Click Me</button> <script> // Use jQuery to handle a button click event $(document).ready(function () { $("#myButton").click(function () { alert("Button clicked!"); }); }); </script> </body> </html>

In this example, we use $(document).ready() to ensure that the code inside it is executed only after the document has fully loaded. Then, we use the $ symbol to access jQuery functions, such as $("#myButton") to select the button with the ID "myButton" and .click() to attach a click event handler.

Google CDN

<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head>

Microsoft CDN

<head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> </head>

If you wish to use jQuery CDN other than Google or Microsoft hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Conclusion

A jQuery Content Delivery Network (CDN) is a convenient way to include the jQuery library in web projects. By referencing the jQuery library hosted on a CDN through a <script> tag in your HTML, you can use the speed and reliability of a third-party server to load jQuery, making it readily available for use in your web page's JavaScript code without the need for local installation or hosting.