Russel Riehle Russel Riehle - 2 months ago 5
Javascript Question

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?

Answer

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();
}
Comments