2

I have a TextBox and a Button:

enter image description here

If the value inside the Textbox is 1 (just emulating a condition)) I need to load jQuery on the fly and use a document Ready function :

I tried this :

function work() //when button click
{
        if (document.getElementById('tb').value == '1')
        {
                if (typeof jQuery == 'undefined')
                {
                        var script = document.createElement('script');
                        script.src = "http://code.jquery.com/jquery-git2.js";
                        document.getElementsByTagName('head')[0].appendChild(script);
                        $(document).ready(function ()
                        {
                                alert('');
                        });
                }
        }
}

But it says :

Uncaught ReferenceError: $ is not defined

I assume it's because the line : $(document).ready(function ()....

But I don't understand why there is a problem , since i'm, loading jQuery BEFORE I use $...

Question :

How can I fix my code to work as desired ?

JSBIN

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 7
    Why on earth would you load jQuery on demand? Either use it or don't ? – adeneo Aug 19 '13 at 13:08
  • @adeneo cannot upvote enough. This question is a massive over-complication of what should be a simple problem. – Rory McCrossan Aug 19 '13 at 13:09
  • @adeneo There is a CRM system in our company which uses many iframes which hosts pages. some of them related to master pages which includes jQuery and many pages are single on iframe which doesn't has jQuery. that's why. I didnt built it. so - i need to check if there's already jQuery on the page and if there is not - I need to download it . ( this script is running from jscript.js) which all pages have reference to. – Royi Namir Aug 19 '13 at 13:11
  • visit http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file – Satpal Aug 19 '13 at 13:11
  • Then you shouldn't load jQuery when the user types something, but more like [this](http://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/) when the page loads ! – adeneo Aug 19 '13 at 13:15
  • @adeneo The `typeSomething` is for the JSBIN condition sample.( for simplification). – Royi Namir Aug 19 '13 at 13:17
  • 2
    @adeneo, it's a good idea to not load extra libraries unless you need them. It would be wiser to use something like [requirejs](http://requirejs.org/) to perform module loading. – zzzzBov Aug 19 '13 at 13:17
  • @zzzzBov - that's true, but loading jQuery only if the user types "1" is not generally a very good idea. – adeneo Aug 19 '13 at 13:19
  • @adeneo Again , it's for simplification. do you really want to see the whole code just for condition which yields true or false ? anyway - I've edited. – Royi Namir Aug 19 '13 at 13:19
  • 1
    It doesn't matter what the condition is, in my opinion you should load jQuery if it's not already loaded in a parent frame on pageload, not when the user performs some sort of action. I've tried this as well, thinking it would shave some time of the initial pageload, but eventually what you end up with is bad UX and just more problems. Either load it on pageload, or use plain javascript instead. – adeneo Aug 19 '13 at 13:24

2 Answers2

4

You are missing the script onload handler:

var script = document.createElement('script');
// do something with script
// onload handler
script.onload = function () {
     // script was loaded, you can use it!    
};

Your function becomes:

function work() {

    if (document.getElementById('tb').value != '1') { return; }
    if (typeof jQuery != 'undefined') { return; }

    // jQuery is undefined, we will load it
    var script = document.createElement('script');
    script.src = "http://code.jquery.com/jquery-git2.js";
    document.getElementsByTagName('head')[0].appendChild(script);

    // load handler
    script.onload = function () {
        // jQuery was just loaded!
        $(document).ready(function () {
            alert('');
        });
    };
}

Also, do not forget script.onreadystatechange for IE compatibility.

script.onreadystatechange = function () {
    if (script.readyState === 'loaded' || script.readyState === 'complete') {
        // script was loaded 
    }
}

Also seems that YepNope would be a good option, too.

JSBIN DEMO

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
3

Using YepNope would probably a good option in this case.

yepnope([
    {
        test: window.jQuery,
        nope: 'path/url-to-jquery.js',
        complete: function() {
            $(document).ready(function() {
                //whatever you need jquery for
            });
        }
    }
]);

You can just put that in the head of your document, and it will only load jquery if window.jQuery isn't defined. It's much more reliable (and simpler) than script.onload or script.onreadystatechange. the callback complete will only be called once jquery is loaded, so you can be sure that $ will be defined at that point.

Note: if you're using Modernizr.js on your site, there's a good chance yepnope is already bundled into that script.

Jedediah
  • 1,916
  • 16
  • 32