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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With