Search code examples
javascriptjquerycdnfallback

How to wait for document.write to complete


I am trying to write some script fall-back code so that if jQuery and jQuery Validator is not available from a CDN I load a local version. Note that the following script is in a separate file to support Content Security Policy (CSP).

(window.jQuery || document.write('<script src="/js/jquery.js"><\/script>'));
($.validator || document.write('<script src="/js/jquery-validate.js"><\/script>'));

If jQuery is not available a new script tag is written to the end of the document but then the next line errors saying that $ is undefined. How can I wait for the document write to finish loading up the document before executing the next line?


Solution

  • You should utilize the onload event of the <script>. Instead of ducoment.write, add a script tag to the document via DOM manipulation:

    var s = document.createElement('script');
    s.onload = function() {
      // jQuery is now loaded and can be used
    }
    s.src = '/js/jquery.js';
    document.getElementsByTagName('head')[0].appendChild(s);
    

    UPDATE:

    The answer to your question 'how to wait for document.write' is you don't have to because document.write is synchronous. The next line after document.write will only execute once the write method finished writing. However, if you write a <script> tag into the document with an src attribute, the loading of the resource (where src points to) will be asynchronous and will start after write finished in paralell with the next statements. Because it's impossible to tell in advance how long the loading of a resource will take, the only viable approach to be sure everything is available from the external script is the onload event.