Muhammad Rehan Saeed
Muhammad Rehan Saeed

Reputation: 38527

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?

Upvotes: 8

Views: 6435

Answers (2)

marekful
marekful

Reputation: 15361

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.

Upvotes: 8

Wazner
Wazner

Reputation: 29

document.write already blocks execution until the information is parsed and processed. So you don't require any extra code for your example.

On an other note, I would recommend to use DOM injection instead of document.write. document.write delays CSS processing and can cause a FOUC (Flash of unstyled content).

DOM injection can be done as follows:

var scriptElm = document.createElement('script');
scriptElm.src = '/js/jquery.js';
document.getElementsByTagName('head')[0].appendChild( scriptElm );

// Check if jQuery is loaded here

Upvotes: 2

Related Questions