Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically add external scripts using jQuery?

I thought that I could just use jQuery's .append() and add them to the head, but that doesn't seem to be working for my external scripts (Knockout.js).

Here's my code that runs when the page loads. It seems to be working for the stylesheet, but not for the external scripts.

if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.8.0') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
        "http://code.jquery.com/jquery-1.8.0.min.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
              scriptLoadHandler();
          }
      };
    } else {
      script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

function main() { 
        jQuery(document).ready(function($) {
            $("head").append("<script type='text/javascript' src='http://knockoutjs.com/js/jquery.tmpl.js'></script>");
            $("head").append("<script type='text/javascript' src='http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js'></script>");
            $("head").append("<link href='style.css' rel='stylesheet' type='text/css' />");

            // Then it appends the necessary HTML code [...]
        });
    }

Here's my test environment where you can see my current code in action with Firebug.

Here's what I'm seeing in Firebug after the page loads:

enter image description here

EDIT: It looks like it's having issues with the Knockout.js scripts in my code, so I'll look into those. Thank you for the comments and answer regarding dynamic scripts. I learned something :)

like image 681
Jon Avatar asked Feb 07 '26 01:02

Jon


2 Answers

Have you tried jQuery.getScript() ? It basically loads a script from the server and then executes it.

 $.getScript("yourScript.js", function(){});
like image 81
alemangui Avatar answered Feb 08 '26 13:02

alemangui


Try to add scripts this way, I have seen that issue before in some browsers.

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = script_url;
$("head").append( script ); 
like image 34
Gurpreet Singh Avatar answered Feb 08 '26 15:02

Gurpreet Singh