Search code examples
javascripthtmljqueryknockout.jscdn

Using CDN clears page content


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?)


Solution

  • 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.