Here's my issue - I need to dynamically download several scripts using jQuery.getScript() and execute certain JavaScript code after all the scripts were loaded, so my plan was to do something like this:
function GetScripts(scripts, callback) { var len = scripts.length for (var i in scripts) { jQuery.getScript(scripts[i], function() { len --; // executing callback function if this is the last script that loaded if (len == 0) callback() }) } }
This will only work reliably if we assume that script.onload events for each script fire and execute sequentially and synchronously, so there would never be a situation when two or more of the event handlers would pass check for (len == 0) and execute callback method.
So my question - is that assumption correct and if not, what's the way to achieve what I am trying to do?
Running JavaScript on GraalVM supports multithreading. Depending on the usage scenario, threads can be used to execute parallel JavaScript code using multiple Context objects, or multiple Worker threads.
JavaScript is a single-threaded language and, at the same time, also non-blocking, asynchronous and concurrent. This article will explain to you how it happens.
As you may probably know, Javascript is single-threaded. To clarify better, this means that one single thread handles the event loop. For older browsers, the whole browser shared one single thread between all the tabs.
Q: Ok, is Javascript single-threaded? A: Yes, Javascript “runtime” is single-threaded. It executes the javascript program. It maintains a single stack where the instructions are pushed to control the order of execution and popped to get executed.
No, JavaScript is not multi-threaded. It is event driven and your assumption of the events firing sequentially (assuming they load sequentially) is what you will see. Your current implementation appears correct. I believe jQuery's .getScript()
injects a new <script>
tag, which should also force them to load in the correct order.
Currently JavaScript is not multithreaded, but the things will change in near future. There is a new thing in HTML5 called Worker. It allows you to do some job in background.
But it's currently is not supported by all browsers.
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