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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With