Dynamically and synchronously load JavaScript file from a different domain

9.6k views Asked by At

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.

5

There are 5 answers

0
Jeff Walden On BEST ANSWER

It's not possible to synchronously execute a script at a URL. Note further that synchronous anything, when networks (or even file systems!) are involved is a Bad Idea. Someone, sometime, somewhere will be on a slow system, or a slow network, or both, and suddenly you've just hung their UI in the process.

Synchronous is bad. Asynchronous with callbacks is good.

Note that, as a worst-case hack, you could overwrite $ with your own function, which returned an object with just the right properties, and you could semi-lazily evaluate all actual calls. This of course breaks if you start relying on immediate execution of the calls, or on their execution being intermingled with the evaluation of arguments, but in the worst case it's not completely implausible.

4
simshaun On

You should be able to use .getScript()

Edit: Cross-domain requests are always loaded asynchronously in jQuery.

2
philwinkle On

A great library called YepNope exists for loading javascript dependencies from any location - developed by a member of the yayQuery podcast. It can be found here: http://yepnopejs.com/

2
Alex Sexton On

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

0
Shoib Mohammed A On

LABjs.js, is nice library. I used it works well.

http://labjs.com/