Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load jQuery in another js file

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?

like image 678
Moein Hosseini Avatar asked Nov 15 '11 16:11

Moein Hosseini


People also ask

Can I put jQuery in a JS file?

Your JavaScript file ( scripts. js ) must be included below the jQuery library in the document or it will not work. Note: If you downloaded a local copy of jQuery, save it in your js/ folder and link to it at js/jquery. min.

How do I include an external js file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.

Where do I put jQuery in HTML?

Step 1: Firstly, we have to open that Html file in which we want to add the jQuery using CDN. Step 2: After then, we have to place the cursor between the head tag just before the title tag. And, then we have to use the <script> tag, which specify the src attribute for adding.


1 Answers

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.

like image 143
Darin Dimitrov Avatar answered Oct 21 '22 00:10

Darin Dimitrov