0

I am trying to load an external javascript file from within javascript but I cannot seem to get it to work. Am I doing something wrong?

sample file of my work

function loadJs() {
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js")
document.body.appendChild(fileref); }
3
  • Why do you want to load jquery dynamically? Perhaps there is a better solution. Commented Dec 25, 2011 at 20:32
  • It is part of a project I am working on. Realistically, I would just load it in HTML using <script> :) Commented Dec 25, 2011 at 20:43
  • Are you sure document.body exists when this runs? If this runs from the head, document.body won't exist yet. Commented Dec 25, 2011 at 20:47

2 Answers 2

7

Perhaps you are trying to access the jQuery API before it is fully loaded. You can add a callback parameter to the loadJs function like this:

function loadJs(src, callback) {
    var s = document.createElement('script');
    document.getElementsByTagName('head')[0].appendChild(s);
    s.onload = function() {
        //callback if existent.
        if (typeof callback == "function") callback();
        callback = null;
    }
    s.onreadystatechange = function() {
        if (s.readyState == 4 || s.readyState == "complete") {
            if (typeof callback == "function") callback();
            callback = null; // Wipe callback, to prevent multiple calls.
        }
    }
    s.src = src;
}

loadJs('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', function() {
    $('body').append('<p>It works!</p>');
});

Tested in chrome, FF, ie8. Fiddle: http://jsfiddle.net/Umwbx/2/

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

2 Comments

@David I have updated your answer by adding a correct implementation of onreadystatechange.
This script helped me so solve $.getScript problems in android 4.0.* and no more "unknown chromium error 6"
0

Use code similar to this:

function loadJs() {
    var s = document.createElement('script');
    var c = document.getElementsByTagName('script')[0];
    s.type = 'text/javascript';
    s.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    c.parentNode.insertBefore(s, c);
}

2 Comments

I tried your above code in Chrome and it did not seem to be working. When I mouse over the word 'hello', the background colour does not change.
It is working, if you inspect the code in Chrome Developer Tools / Firebug you will see the script tag added. The background color is not changing because you are calling the jquery code before jquery is even loaded.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.