Pratik Bhoir
Pratik Bhoir

Reputation: 2144

load knockout.js lib at runtime

I want to load knockout.js lib at run time. It gets loaded but after applyBindings() the html body tag i.e <body></body> disappers and throws

Uncaught TypeError: Cannot read property 'nodeType' of null

        var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js");
        document.getElementsByTagName("head")[0].appendChild(script);
        ko.applyBindings(viewModel);

I just dont understand, why the body element gets emptied.
P.S. : It works perfectly, if I add knockout.js lib beforehand.

Upvotes: 3

Views: 314

Answers (1)

haim770
haim770

Reputation: 49095

First, you're using ko without making sure that the script is already loaded. You need to pass a callback using the onload property:

script.onload = function() {
    ko.applyBindings(viewModel);
}

Also, Knockout complains because you're calling applyBindings before the DOM is ready. Try to run your code as part of a DOMContentLoaded event callback:

document.addEventListener("DOMContentLoaded", function() { 
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js");
    document.getElementsByTagName("head")[0].appendChild(script);

    script.onload = function() {
        ko.applyBindings(viewModel);
    }
});

See Fiddle

Upvotes: 2

Related Questions