Russel Riehle Russel Riehle - 9 months ago 39
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 = "";

And in my index.html

I did this:

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

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



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


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





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


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

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



if(typeof jQuery=='undefined') {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = '';
    jqTag.onload = fnjquery;
} else {