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.
A/B testing scripts can be loaded in two ways: Synchronously, where scripts are loaded sequentially, one after another, starting with the <head> tag. Asynchronously, where some scripts can be loaded simultaneously.
You can either send the JS to your server and have it pass it to a different server (probably on the same box) that then serves the iframe or you can use window. postMessage() to deliver the JS text to the other cooperating iframe and execute it there.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With