Reputation: 2144
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
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