admin管理员组

文章数量:1391964

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", ".7.1/jquery.min.js")
document.body.appendChild(fileref); }

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./ajax/libs/jquery/1.7.1/jquery.min.js")
document.body.appendChild(fileref); }
Share Improve this question asked Dec 25, 2011 at 20:24 JonJon 8,55131 gold badges96 silver badges150 bronze badges 3
  • Why do you want to load jquery dynamically? Perhaps there is a better solution. – PeeHaa 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> :) – Jon 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. – Dagg Nabbit Commented Dec 25, 2011 at 20:47
Add a ment  | 

2 Answers 2

Reset to default 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 == "plete") {
            if (typeof callback == "function") callback();
            callback = null; // Wipe callback, to prevent multiple calls.
        }
    }
    s.src = src;
}

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

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

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./ajax/libs/jquery/1.7.1/jquery.min.js';
    c.parentNode.insertBefore(s, c);
}

本文标签: Load External JavaScript FileStack Overflow