How to include jQuery

Rumman Ansari   Software Engineer   2023-03-23   95 Share
☰ Table of Contents

Table of Content:


How to include jQuery

Using jQuery - Method 1

There are two methods to include jQuery in your page.

Method 1: The whole jQuery library is present in a single .js file. Download the jQuery .js file from the official website and include it in your page inside the script tag.

Example:


<script src="C:\Users\JQuery\jquery-3.2.1.min.js"> </script> 
//Include the path of the js file in src attribute.
Using jQuery - Method 2

Instead of downloading the .js file, you can also include the .js file from CDN(Content Delivery Network). There are a lot of famous CDN available.

Example :


Google CDN: 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Microsoft CDN: 
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>

Advantage of using CDN is that, the user might already have the js file in the cache. Hence the browser will load the js file from cache instead of downloading. This makes the page load fast.

Now you might have a question... Where should I code?

You can include jQuery code inside the script tag of html file or create a .js file with the code and include that file in the html page using script tag.

jQuery Basic Syntax

The syntax for writing a jQuery code is:


$(selector).action()
  • $ - used to access jQuery.

  • selector - identifies the HTML element on which action needs to be performed.

  • action() - jQuery event call that will perform a specific task.

All the jQuery code must be executed only after the page loads completely. Else, the selector will not be able to find the required HTML element from the page.

All the jQuery code will be written inside following function, as it executes only after the page loads completely.


$(document).ready(function(){
//some code
});

The ready function can also be writtern by simply using


$(function(){ 
//some code   
});