Russel Riehle
Russel Riehle

Reputation: 267

How can I check if jquery is loaded from external JS file?

I have an external JS file to manage all script in my page. I want to write in this file some code to check if jquery plugin is loaded and (if not) load it!

I tried to begin my myScripts.js file with this code:

if (typeof jQuery == 'undefined') {
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
}

And in my index.html

I did this:

<!DOCTYPE html>
<html lang="pt-br">

    <head>
        <script src="myScripts.js"></script>

    </head>

    <body>

        <button id="test">test</button>

        <script>

        $('#test').click( function() {

            alert('clicked');

        });

        </script>
    </body>

</html>

But it's not performing the alert dialog.. What's wrong?

Upvotes: 0

Views: 1298

Answers (3)

Kshri
Kshri

Reputation: 414

Here is a working Fiddle

function myJQueryCode() {
    //Do stuff with jQuery
    $('#test').click( function() {
            alert('clicked');
        });
}

if(typeof jQuery=='undefined') {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
    jqTag.onload = myJQueryCode;
    headTag.appendChild(jqTag);
} else {
     myJQueryCode();
}
<button id="test">
click
</button>

Upvotes: 0

Chetan Gawai
Chetan Gawai

Reputation: 2401

Enclose click event in $(document).ready to ensure that the event gets fired when DOM is ready.

$(document).ready(function(){
$('#test').click( function() {

            alert('clicked');

        });
});

Upvotes: 1

Mannan Bahelim
Mannan Bahelim

Reputation: 1355

When you add the jquery file using the script.it would not available so you have to add onload listener to detect the when it's available.

function fnjquery() {
    $('#test').click( function() {

        alert('clicked');

    });
}

if(typeof jQuery=='undefined') {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
    jqTag.onload = fnjquery;
    headTag.appendChild(jqTag);
} else {
     fnjquery();
}

Upvotes: 0

Related Questions