Dynamically and synchronously load JavaScript file from a different domain

Atanas Korchev picture Atanas Korchev · Feb 16, 2011 · Viewed 9.5k times · Source

I would like to synchronously include a JavaScript file from a different domain via code. This means that using a synchronous XMLHttpRequest will not work. I also want to avoid document.write because my code will be executed when the document is fully loaded. Is this even possible? Does any of the existing JavaScript libraries support that feature?

Basically I want this to work:

<script type="text/javascript">
  $(document).ready(function() {
      load("path_to_jQuery_UI_from_another_domain");
      console.log(jQuery.ui.version); //outputs the version of jQuery UI
  });
</script>

EDIT: My idea is to create a jQuery plugin which loads its JavaScript files based on the enabled features. jQuery plugins can be initialized at any time which means no document.write. It is perfectly fine to load the JavaScript files asynchronously but people expect their plugins to be fully initialized after calling $("selector").something();. Hence the need of synchronous JavaScript loading without document.write. I guess I just want too much.

Answer

Alex Sexton picture Alex Sexton · Feb 17, 2011

The only way to synchonously load files is to document.write a script tag into your page. This is generally considered a bad practice. There is probably a better way to do what you actually want, but, in the spirit of transparency:

document.write('<script src="http://otherdomain.com/script.js"></'+'script>')

should do the trick. You have to escape the closing script tag so the parser doesn't close the script tag that you wrote.

**Note that you can't dynamically load scripts that contain a document.write