Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically loading JavaScript synchronously

Tags:

javascript

I'm using the module pattern, one of the things I want to do is dynamically include an external JavaScript file, execute the file, and then use the functions/variables in the file in the return { } of my module.

I can't figure out how to do this easily. Are there any standard ways of performing a pseudo synchronous external script load?

function myModule() {     var tag = document.createElement("script");     tag.type = "text/javascript";     tag.src = "http://some/script.js";     document.getElementsByTagName('head')[0].appendChild(tag);      //something should go here to ensure file is loaded before return is executed      return {         external: externalVariable      } } 
like image 236
Eric Schoonover Avatar asked May 21 '10 04:05

Eric Schoonover


People also ask

Are script tags loaded synchronously?

Freshmarketer JS script can be loaded and executed in two ways: Synchronous code: Scripts are loaded and executed sequentially along with the other web page components. Each time a function is called, the program execution waits until the function is returned before executing the next line of code.

What is script async?

The async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously as soon as it is available. Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).


1 Answers

There is only one way to synchronously load and execute a script resource, and that is using a synchronous XHR

This is an example of how to do this

// get some kind of XMLHttpRequest var xhrObj = createXMLHTTPObject(); // open and send a synchronous request xhrObj.open('GET', "script.js", false); xhrObj.send(''); // add the returned content to a newly created script tag var se = document.createElement('script'); se.type = "text/javascript"; se.text = xhrObj.responseText; document.getElementsByTagName('head')[0].appendChild(se); 

But you shouldn't in general use synchronous requests as this will block everything else. But that being said, there are of course scenarios where this is appropriate.

I would probably refactor the containing function into an asynchronous pattern though using an onload handler.

like image 111
Sean Kinsey Avatar answered Sep 20 '22 21:09

Sean Kinsey