Open In App

Check if a jquery has been loaded or not

Last Updated : 16 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a document, The task is to determine whether JQuery has been loaded or not, If not then load it dynamically using JavaScript. Below are the examples to check: 

Approach:

  • First, check if it is loaded.
  • If not loaded then load it dynamically, create a script element and add properties like(type, src) to it and then finally append it at the end, inside of the head element.

Example 1: In this example, the JQuery is already loaded so the message ‘Script already loaded!’ prints on the screen. 

html




<script src=
</script>
  
<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<button onClick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up =
        document.getElementById('GFG_UP');
    var down =
        document.getElementById('GFG_DOWN');
    up.innerHTML =
    "Click on button to check whether JQuery is loaded";
      
    function GFG_Fun() {
        if (!window.jQuery) {
            var el = document.createElement('script');
            el.type = "text/javascript";
            el.src =
            document.getElementsByTagName(
            'head')[0].appendChild(el);
            down.innerHTML = "Script loaded successfully!";
        } else {
            down.innerHTML = "Script already loaded!";
        }
    }
</script>


Output:

Check if a jquery has been loaded or not

Check if a jquery has been loaded or not

Example 2: The src attribute of script element is changed to sc. In this example, the JQuery is not loaded so message ‘Script loaded successfully!’ prints on screen after successful loading. 

html




<script src=
</script>
  
<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<button onClick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up =
        document.getElementById('GFG_UP');
    var down =
        document.getElementById('GFG_DOWN');
    up.innerHTML =
    "Click on button to check whether JQuery is loaded";
      
    function GFG_Fun() {
        if (!window.jQuery) {
            var el =
                document.createElement('script');
            el.type = "text/javascript";
            el.src =
            document.getElementsByTagName(
            'head')[0].appendChild(el);
            down.innerHTML = "Script loaded successfully!";
        } else {
            down.innerHTML = "Script already loaded!";
        }
    }
</script>


Output:

Check if a jquery has been loaded or not

Check if a jquery has been loaded or not



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads