11

I want to load a javascript file at the end of jquery.ready so that the code in my ready handler doesn't have to wait to execute until this large javascript file is loaded.

My jquery.ready code doesn't rely on this javascript file at all.

Would this be a good way to do that?

$(function(){
    ...
    ...      
    $('head').append('<script type="text/javascript" src="/largejs.js"></script>');
});

4 Answers 4

29

Use .getScript: http://api.jquery.com/jQuery.getScript/

$(document).ready(function(){
    ...
    ...
    $.getScript("largejs.js");
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Emil, I didn't know about this and it helped a lot
@ShahadatHossainKhan Of course it won't work without JQuery, but the question is specifically about how to do this with JQuery.
3

solution will check jquery already loaded, if not it will check after some time here 500ms and loop until it found jquery

function loadScriptAfterJQueryReady(jsFile) {
    setTimeout(function () {
        var loadScript=true;
        if (typeof jQuery == 'undefined') {
            if (typeof window.jQuery == 'undefined') {
                /* jQuery is not loaded */
                loadScript=false;
                loadScriptAfterJQueryReady(jsFile);
            }else{
                /* jQuery is loaded */
            }
        } else {
            /* jQuery is loaded */
        }
        if(true==loadScript) jQuery.getScript(jsFile);
    }, 500);
}
loadScriptAfterJQueryReady("my.js");

Comments

1

The quoted "</script>" tag will actually end your block of JavaScript prematurely.

I'd use this method:

var newScript = $(document.createElement('script'));
newScript.src="/largejs.js"

1 Comment

don't forget to append it as a child of the document.body or a head element. BTW, you can get rid of the $ and parens if you aren't using jquery.
0

If your application is new and not too far along yet, you could get a lot out of using LABjs for that purpose. It allows all your script files to load in parallel or, even, at any other time that you prefer (on demand). http://labjs.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.