Load Scripts Asynchronously

load scripts asynchronously

A couple solutions for async loading:

//this function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}

If you've already got jQuery on the page, just use:

$.getScript(url, successCallback)*

Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.

It's not possible to tell specifically what your issue is without seeing the code.

The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.

If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).

* scripts loaded with $.getScript will likely not be cached


For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:

function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}

Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).

This has the added bonus of being able to detect and handle failures, for example one could call...

loadScript(cdnSource)
.catch(loadScript.bind(null, localSource))
.then(successCallback, failureCallback);

...and it would handle CDN outages gracefully.

Load scripts asynchronously using getScript

The second Deferred object becomes resolved as soon as the DOM finishes loading, it does not wait for the getScript() methods (since those could theoretically be executed way later, so they don't get special treatment).

The first Deferred object becomes resolved when /script.js finishes loading, not when all the scripts have finished loading. At that point, the doneCallback to load /scripts2.js is called, but the doneCallback for the $.when(...) is also already called since both Deferred objects it was passed are resolved at that point.

You should put the $(this).testscript(); callback as the doneCallback for the getScript("/js/testscript.js"), not for the when(...) statement, like this:

$.when(
$.getScript('/script.js').done(function() {
$.getScript('/script2.js'),
$.getScript('script3.js').done(function() {
$.getScript('/script4.js').done(function() {
$.getScript('/script5.js').done(function() {
$.getScript( "/js/testscript.js" ).done(function() {
console.log("LOADED 2");
$( ".test" ).each(function() {
console.log("LOADED 1");
$(this).testscript(); //function from /js/testscript.js
});
})
})
})
})
}),
$.Deferred(function(deferred) {
$( deferred.resolve );
})
).done(function() {
console.log("TEST");
});

Using async and defer to load scripts in order

The answer is that you lose guarantees about the order scripts are executed if you use async or defer.

async scripts are executed asyncronously, there are no guarantees as to which order there are. defer scripts are executed after the document has been parsed, but there are no guarantees as to whether they will be executed in order. (Have a look at this question about defer scripts specifically.)

Unfortunately, in your case, you have to run jquery.js synchronously by removing the defer and async attributes.

Looking forward, as we move to modules, specifying dependencies and loading them just in time (and only once) will be made much easier.

Loading/Appending JS script asynchronously

This warning will continue to happen as long as you inject the script to the body of the document.

I'd recommend using $.getScript as this will load the script correctly. I do not really understand why you'd want all javascripts to be in the same page from the first place.
You probably want to have them in a separate file anyway for easier maintenance down the road and separation of concerns.

You can also use vanilla javascript for that:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('src','your_script.js');
head.appendChild(script);

If you insist on doing it this way - try injecting it directly to the head of the document and not the body and see if that helps.

On a more general note - seems like you're building a single page application (SPA) - have you looked into JS frameworks like Angular, Backbone, etc? they will handle all the heavy lifting for you and will help you scale your application better. This smells a little bit like trying to re-invent the wheel and could be a great thing as an educational process but might not be such as good idea in the long run.

Hope this helps.

How to load Scripts async with Angular

You can use app.run which will run like a main method before the app loads everything

     app.run(["scriptService"],function(scriptService){
scriptService.GetScripts()
.then(function(success){console.log("loaded test");},
function(error){ console.log("not loaded");}
}]);

Next all you have to do is make a script Service.

    app.factory("scriptService", ["$http", function ($http) {
this.GetScripts = function ()
{
return $http.get(""https://www.website.com/crsc/scripts/script.js") .then(function(result) { return result});

}

but in reality why do you not just import the script through a script tag?
Loading a script async, since op didnt know that was an option I thought I would include it here ww3 schools async loading

  <script src="demo_async.js" async></script>

definition and Usage 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).

Note: There are several ways an external script can be executed:

If async is present: The script is executed asynchronously with the
rest of the page (the script will be executed while the page continues
the parsing) If async is not present and defer is present: The script
is executed when the page has finished parsing If neither async or
defer is present: The script is fetched and executed immediately,
before the browser continues parsing the page Browser Support The
numbers in the table specify the first browser version that fully
supports the attribute.

Can we use async attribute for script loaded dynamically?

By script loaded dynamically, if you mean adding javascript code dynamically to your page, then the answer is No.

async attribute can only be used on loading external scripts that are referred to via a URL specified in src attribute.

The async attribute is only for external scripts (and should only be used if the src attribute is present)

Example, You can load only scripts like this asyncronously

 <script src="external-file.js" async></script> 


Related Topics



Leave a reply



Submit