6

I have a JavaScript file, which also uses jQuery in it too. To load it, I wrote this code:

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    head.appendChild(script)
}

include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
alert("1");

$(document).read(function(){});
alert("2");

This fires alert("1"), but the second alert doesn't work. When I inspect elements, I see an error which says that $ in not defined.

How should I solve this problem?

1

2 Answers 2

24

You need to execute any jQuery specific code only once the script is loaded which obviously might happen at a much later point in time after appending it to the head section:

function include(filename, onload) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    script.onload = script.onreadystatechange = function() {
        if (script.readyState) {
            if (script.readyState === 'complete' || script.readyState === 'loaded') {
                script.onreadystatechange = null;                                                  
                onload();
            }
        } 
        else {
            onload();          
        }
    };
    head.appendChild(script);
}

include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
    $(document).ready(function() {
        alert('the DOM is ready');
    });
});

And here's a live demo.

You may also take a look at script loaders such as yepnope or RequireJS which make this task easier.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for a detailed answer without immediately resorting to a script loader (which is probably what I would have done :)
-1

The problem here is probably that, even though you include the script, it doesn't mean it is loaded when you try to do $(document).ready(function(){});. You could look into Google Loader to prevent this problem http://code.google.com/intl/fr-FR/apis/loader/

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.