StepTNT
StepTNT

Reputation: 3967

ReferenceError: ko is not defined when loading from jQuery

I'm trying to load KnockoutJS using the jQuery's getScript function and, after countless tests, I'm still stuck with the

ReferenceError: ko is not defined

error.

Here's a simple code that I'm running in my script to test if everything works (I've also tried to write this code directly into FireBug but I got the same results):

$.getScript('http://knockoutjs.com/downloads/knockout-3.2.0.js', 
    function(d,s,j){
        console.log(d);
        console.log(s);
        console.log(j);
        console.log(ko);
});

Checking the console shows those messages:

undefined

success

Object { readyState=4, status=200, statusText="success", other elements...}

ReferenceError: ko is not defined

and I've no idea on what's going on.

As a side note, I've also tried those urls with the same results

EDIT:

Based on @T.J. Crowder's first answer I also tried this code

$("<script>")
.on("load", function() {
    // It's loaded now
  console.log("success");
})
.on("error", function() {
    // It failed to load
  console.log("error");
})
.attr("src", "http://knockoutjs.com/downloads/knockout-3.2.0.js");

but nothing is shown on the console.

Upvotes: 1

Views: 10892

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075129

getScript uses XHR (ajax), which is controlled by the Same Origin Policy. So you can't load scripts from other origins unless they enable your origin via CORS.

Instead, simply add a script tag referencing the script you want to load.

var scr = document.createElement('script');
scr.onload = function() {
  display("Loaded: " + typeof ko);
};
scr.onerror = function() {
  display("Error");
};
scr.src = "http://knockoutjs.com/downloads/knockout-3.2.0.js";
document.querySelector("script").parentNode.appendChild(scr);

function display(msg) {
  $("<p>").html(String(msg)).appendTo(document.body);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 2

Related Questions