2

I have a reference to a CDN on my page with a fallback script in case this cannot be reached.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.min.js" integrity="sha384-PA7LgTHoYGwvEy2evWvC3sNOQlmK/vfk//sStiSk3QK3fUDO8oN3VKvHgSPyVKqx" crossorigin="anonymous" ></script>
<script type="text/javascript">(window.ko)||document.write('<script type="text/javascript" src="/bundles/knockout?v=20200622" ><\/script>');</script>

This reference is placed on html file that is dynamically loaded by ajax and added with jQuery:

$.ajax({ url: action, cache: false }).done(
   function (data, textStatus, jqXHR) { contentCtrl.html(jqXHR.responseText); }
); 

But when this html is added on the page, the page is cleared, and only the html for the fallback remains. Anyone know how I can solve this? (I suspect this has something with the document.write that is executed from the fallback?)

RubenHerman
  • 1,674
  • 6
  • 23
  • 42

1 Answers1

2

According to here document.write clears the page by calling document.open first after the page is loaded (which is your use case since I assume your ajax call happens after loading the page). You might want to look into $.getScript instead.

Richard Yan
  • 1,276
  • 10
  • 21
  • This looks indeed like it's the problem, but I don't understand why it is executed, since "window.ko" should already be "true" and thus shouldn't execute the fallback... – RubenHerman Jun 22 '20 at 08:59
  • Check [this answer](https://stackoverflow.com/questions/94141/javascripts-document-write-inline-script-execution-order/94744#94744) – Richard Yan Jun 22 '20 at 09:21