Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 305
Pratik Bhoir Avatar asked Jan 01 '26 04:01

Pratik Bhoir


1 Answers

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

like image 105
haim770 Avatar answered Jan 03 '26 17:01

haim770



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!