When I make a website using javascript, do I have the opportunity to take advantage of multiple threads on the client's computer?
I know web programming can give you access to multiple asynchronous http or networking requests. I'm wondering about actual in-browser processing.
Web Workers is the way to go...
It is a HTML 5 feature which allows running multiple threads (workers) on the client. This feature is currently a working draft.
You can start any number of workers for a page, and each worker can 'post' their state or the result to the main thread.
Have a peek at this MDN post https://developer.mozilla.org/En/Using_web_workers
Also, the link posted by SRN is also very useful ( http://www.html5rocks.com/en/tutorials/workers/basics/)
Also mind that the browser support is still not good. http://caniuse.com/webworkers
It's best you have a fall-back method in case you hit a browser that's un-supported. Also note that Chrome used to have a bug where the web worker can can actually hang the Chrome UI. May be it's now fixed, but look out.
There are things called "WebWorkers" that provide some degree of concurrency. They interoperate with "normal" code via a message passing paradigm kind-of like Erlang processes (though not nearly as sophisticated).
It's a new-ish HTML5 thing, and not supported in old browsers of course.
Web Workers is the technology.
A web worker -- as defined by the World-Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG) -- is a JavaScript script -- executed from an HTML page -- that runs in the background, independently of other, user-interface scripts that may also have been executed from the same HTML page
See on usage on MDN too:
Dedicated Web Workers provide a simple means for web content to run scripts in background threads. Once created, a worker can send messages to the spawning task by posting messages to an event handler specified by the creator.
there is multithreaded web programming but there is no multithreaded javascript.
when javascript executes in a browser on the client it is interpreted line by line and won't render anything while it is executing.
you can tap into open source libraries to "imitate" multithreading but basically each javascript needs a page to live and run on.
some tricks are to pass long running functions to run inside of an iframe or to use a setTimeout function to do some work for 50 milliseconds at a time until some flag you use to keep track of the job says the work is done like isFinished == true
the latest versions of flash player allows multithreading in it but it is limited to very basic usage across a single domain.
html 5 web workers are another option but won't work in all browsers
Related
I've been reading articles online about what universal javascript is but I'm still not comfortable with the definitions each site is giving which is, "code that can run on the client and server." Does this mean that a node.js app is inherently universal javascript because it will have javascript running in the client side and server side. Or does universal javascript have to do with server side rendering then client side rendering?
Preface: I cannot find any highly-authoritative (e.g. ECMA, Microsoft, Mozilla or Google) source that provides a strict definition of "universal JavaScript" or "isomorphic JavaScript" - at most I've found a few blog posts (albeit by influential personalities) however I can see why a newcomer might be confused.
It seems there are two definitions going around which are similar, but with crucial differences:
1. To refer to JavaScript which runs anywhere
This definition refers to JavaScript which does not take a dependency on any specific client-side or server-side API, instead they only make use of features present in JavaScript's built-in library (String, Array, Date, function, Math etc) or on other libraries that also similarly restrict their dependencies (a transitive relation).
Remember that "JavaScript" does not mean that the DOM API, AJAX, HTML5 <canvas> (and so on) are available - it just means the JavaScript scripting language is being used - that's it. JavaScript has been available outside of web-browsers for over 20 years now (Windows support JavaScript as a shell-scripting language in cscript.exe/wscript.exe and ASP 3.0 supported server-side JScript as an alternative to VBScript - and the .NET Framework has "JScript.NET" too).
So in this case, if you wrote a library that adds some useful string functions, which only references String, then that script would work without issue in a Node.js server environment or an in-browser environment.
But if your script ever used the window object (only present in browsers) or express (a library only for Node) then it loses "universal" status because it cannot "run everywhere".
2. To refer to JavaScript which renders the same HTML whether on the server or on the client
e.g. http://isomorphic.net/
This definition is actually a strict subset of the first definition: as the same script must (by definition) run inside both a server/Node.js context, but also a browser DOM context - and when it runs it generates content (typically HTML) that is then displayed in the user's browser (and by doing this it must take a dependency on both a Node API and the W3C DOM - so then it cannot strictly run "anywhere" because neither are available in a cscript.exe environment, for example.
Note: There is debate if use of XMLHttpRequest or fetch makes a script universal or not - as their presence is not guaranteed (as technically they're part of the DOM, not JavaScript's built-in library).
In this 2015 blog post ( https://medium.com/#ghengeveld/isomorphism-vs-universal-javascript-4b47fb481beb ) the author argues that only the term "isomorphic JavaScript" should be used to refer to rendering code that runs in both browser and server environments, while "universal JavaScript" should refer to truly portable, environment-agnostic, JavaScript (i.e. my first definition).
Nowadays Single Page Applications have become very popular but they have problems, SEO, for example.
So, how does an SPA work? JavaScript loads in the browser and loads data from an API. Most of the rendering is done on the client Side. But search engine bots have a hard time indexing the page because it doesn't have much without JS.
Now, Universal/Isomorphic App comes to the rescue. At the initial page load, the original page renders on the server. After that, the app works like an SPA. It's got better SEO because when a search engine bot asks for a page, the server returns the whole rendered HTML page, with content and meta tags.
Edit
An isomorphic app can be done with JavaScript (Node.js), PHP or some other language, but if that app written with Node.js, then we can call it universal as both the backend and frontend are in JavaScript.
I'll try to explain it with examples, even if other answers seem already accurate.
A basic example
Imagine you develop a SPA that render an Hello World message. This means that your browser loads an HTML file with a <script> tag (or the reference to a JS file) that actually makes this happen. You can prove that "Hello world" is generated by JavaScript in the client browser, because if you deactivate JavaScript you won't see any message.
Now isolate the code that prints the string "Hello World", it doesn't need much to be adapted and work in the server side. In fact, the server just needs to send an HTML string that "contains" the <h1>Hello World</h1> inside its body.
So what it makes it universal/isomorphic? The fact that the code can understand in which environment it runs (the browser, the server or possibly an other environment) and it keeps functioning. Remember: code usually only runs in one of the two environments, the thing is that you wrote some common code that can run in both environments (universal).
The behavior of a more complex Universal App
Imagine that you struggle to develop a new Universal website. The code can acknowledge in which environment it is running and work just fine. So you have, let's say, 80% of your code that is shared, it doesn't even need to know the environment, and the rest of your code is there to managing the fact that your app can be used in the client or in the server.
How does this work?
The client first contacts the server that returns some HTML to the client with all the content of the page, elaborated in the server. So the server renders the application. In the mean time the browser downloads the script file where your single page can work in the client. The client is now rendering the same page again. You won't see anything, because if it is properly done, it will just be the same (of course all the animations and real time features have to work client-side, so you will eventually see your animations starting)
When the user clicks an internal link or uses an interactive feature, or eventually fills out and submits a form, the client-side code is in use. The server doesn't get any request, especially assuming that all the interaction are abstracted in an API that is not our isomorphic app.
If the user goes crazy and wants to deactivate JavaScript, how do you assure that, for example, forms still work? Here is a trick you can use:
<form
method="post"
action="/api/fakeBackendRoute"
onSubmit={this.handleSubmit}
>
[input fields here]
</form>
When the client JS is available, the handleSubmit is executed and the propagation of the event is prevented. This way the server side code will never fire.
If the client JS is disabled, then handleSubmit will never be executed and you have to care that your /api/fakeBackendRoute will handle the data exactly how the client would.
Why do people use it?
In my opinion the difficulty of undertaking the development of an Universal App is often underestimated. Good reasons to use it are:
Be more SEO friendly
Support very old browsers. For example, if you want to support IE8, you could do something like this:
<!--[if gt IE 8]><!-->
<script src="yourfile.js"></script>
<!--<![endif]-->
Be more accessible for people that don't want to use JavaScript
Other reasons could be:
Performance, if it matters to your application. You can improve your response time by using, for example, a lot of Node capabilities to stream your HTML string in the first request, and eventually later be more in the client, where things will be likely faster. But you could decide whether it is faster to render on the client or on the server, depending on the content and how you create your assets.
If someone knows other good reasons, just comment below and I will add them.
Some good reference links:
https://medium.com/airbnb-engineering/isomorphic-javascript-the-future-of-web-apps-10882b7a2ebc
https://medium.com/front-end-developers/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4
https://github.com/xgrommx/awesome-redux
I am no beginner in javascript. I am actually working on this for past 3-4 months but today I read this statement about "What is JavaScript?"
JavaScript is single-threaded, non-blocking, asynchronous, concurrent language.
and I was lost. If JavaScript is single-threaded, how can it be concurrent and how can it be asynchronous because you need to keep track what your async code is doing and without another thread, it is impossible to track 2 or more code at a same time?
Ah.. here's the thing:
JavaScript is single threaded, but it has a lot of spare time on its hands.
When it is waiting for something to load out off the network, or its waiting for something off disk or waiting for the OS to hand something back to it, it can run other code.
setTimeout(function() {
// Do something later.
}, 1000);
While it is waiting for that timeout to return an execute that code, it can run code from OTHER timeouts, or network calls or any other async code in the system. It only runs ONE block of code at a time, however, which is why we say it is single threaded.
That thread can just bounce around. A lot.
And, as others have said, there are web workers and service workers, but those run VERY isolated from your main thread. They can't change values behind your main thread's back.
Updated per comment
The event loop works by:
Waiting for an event
Handling that event.
JavaScript is, indeed, blocked while handling an event. While code is running, nothing else in that page (assuming browser main thread) can run.
It isn't a literal event loop as you would have in C or C++, not as far as the JS is concerned. It's just events waiting to happen.
/// Sample code
document.addEventListener("click", function() { /* Handle click */ });
window.addEventListener("load", function() { /* handle load */ });
In this case, have two event listeners in our code. The JS engine will compile, then execute those two statements. Then, for all intents, "sleep" while waiting for something to happen. In reality, that same thread may handle various house-keeping tasks like drawing the HTML page, listening for move movements and emiting all sorts of events, but that doesn't matter for this discussion.
Then, once the rest of the page is loaded, the browser will emit a load event, which will be caught the listener and some more code will be run.
Then it will go back to idling until someone clicks on the document, then more code will run.
If we change the code to this:
document.addEventListener("click", function() {
while(true);
});
then when someone clicks on the document, our thread will go into an endless loop and all browser activity in that window will cease. Might even freeze the entire browser, depending in which one you are running.
Eventually, the browser will give a chance to kill that task so you can have your system back.
Latest Update
If you are aware of Webassembly there is a proposal in place for Threads via natively compiled modules
pthreads-style read this git issue tracker link(1073)
In continuation with #Jeremy J Starcher answer.
Javascript is always been single threaded runtime using asynchronous, non-blocking and event-driven models of execution.
To know more about event loop execution in JS i highly recommend you to watch this
Youtube video. Simply superb explanation by Philip Roberts.
Good olden days, developers would beat around the bush to achieve similar to thread model using
setTimeout with 0 - milliseconds or setIntervals : Basically instructing the engine to take up non-trivial tasks when the engine goes idle or wait mode during a http request or execute the code by switching back and forth in intervals kinda round-robin fashion.
Hidden Iframe : Run a JS code in a sandbox with a bridge to communicate from parent to iframe and vice versa. Technically Iframe doesn't run on separate thread but gets things done as a fake thread.
Fast forwarding [ >>> ] to Multi-threading models by ECMA:
Off late things have changed with the requirement to spawn a thread in JS engines to offload few smaller logical tasks or a network proxy task to a separate thread and concentrate on UI driven tasks like presentation and interaction layer on main thread, which makes sense.
With that requirement in mind ECMA came up with two model/API basically to solve this.
1. Web Worker: (SIC - Mozilla)
Web Workers makes it possible to run a script operation in background
thread separate from the main execution thread of a web application.
The advantage of this is that laborious processing can be performed in
a separate thread, allowing the main (usually the UI) thread to run
without being blocked/slowed down.
[ WebWorker can be split into two ]
Shared Worker
The SharedWorker interface represents a specific kind of worker that
can be accessed from several browsing contexts, such as several
windows, iframes or even workers. They implement an interface
different than dedicated workers and have a different global scope,
SharedWorkerGlobalScope.
Dedicated Worker : Same as Webworker, created using Worker() API but uses DedicatedWorkerGlobalScope
Worker is an object created using a constructor (e.g. Worker()) that
runs a named JavaScript file — this file contains the code that will
run in the worker thread; workers run in another global context that
is different from the current window. This context is represented by a
DedicatedWorkerGlobalScope object in the case of dedicated workers
2. Service Worker (SIC - Mozilla)
Service workers essentially act as proxy servers that sit between web
applications, and the browser and network (when available). They are
intended to (amongst other things) enable the creation of effective
offline experiences, intercepting network requests and taking
appropriate action based on whether the network is available and
updated assets reside on the server. They will also allow access to
push notifications and background sync APIs.
One example usage would be in PWA - Progressive web app to download scripts, lazy loading purposes of assets.
Read this article by Eric Bidelman on HTML5Rocks good explanation about the code itself and implementation
JavaScript may be "single-threaded" (I'm not sure this is really the case), but you can use/create webworkers to run javascript outside the main thread.
So you can run two pieces of code at the same time in parallel.
I think it is wrong to say that a language is this or that when what we really mean is that our programs are this or that.
For example: NodeJS is single-threaded and can run code asynchronous because it uses an event-driven behaviour. (Something comes up and fires an event... Node deals with it and if it is something like an online request, it does other things instead of waiting for the response... when the response comes, it fires an event and Node captures it and does whatever needs to be done).
So Javascript is...
single-threaded? No, as you can use WebWorkers as a second thread
non-blocking? You can write code that blocks the main thread. Just build a for that executes a hundred million times or don't use callbacks.
asynchronous? No, unless you use callbacks.
concurrent? Yes, if you use webworkers, callbacks or promises (which are really callbacks).
Knowing that
Javascript is strictly single threaded and settimeout doesn't spawn
new threads. Instead it follows event-loop model
Worker threads are new HTML5 features and its support is still not
available in all HTML5 browsers
Which one I should be using for background data download purpose? If you have any experience or have any benchmark data available please share.
Not sure how it matters to question, but still for the sake of completeness I would like to mention that data is expected to be in XML format and multiple server-side services will be invoked to get the data. Is there a framework already available which caters to both hand-held device based browsers and desktop based browsers data downloading?
Javascript is single threaded, but that doesn't mean data isn't downloaded in parallel. If you make an asynchronous AJAX call, you are downloading data in the background while the rest of your code is running.
Web workers are meant to do CPU-heavy work off the main thread. They won't help you get data any faster.
Worker thread are not supported on all major browsers yet, so I don't think it will be great idea to involve worker-thread into your design unless you only want to support latest browsers.
All the Ajax calls can be made in parallel, but I guess your problem will be how to know that all ajax call's response has come and data is inserted/updated into browser's database. One way to know that all AJAX responses have been dealt with would be to chain all the AJAX calls. But this will warrant you to hard-code the sequence of AJAX calls into your code-base. If that is not desirable than you would need a separate asynch flow to keep checking if all the AJAX calls have been responded to. You can achieve this by setting a flag for each ajax call and set that to true when the response has been used. Then you will keep checking the status of all the flag in an another flow (started using settimeout).
I am aware of any existing framework to take care of such complex activity, so you will have to write the code yourself for the same. Hope this would have helped you in giving some direction.
Here is a thread where they show how to run a bunch of parallel AJAX calls with JQuery Parallel asynchronous Ajax requests using jQuery
The only reason I can think of to use a worker thread would be to have it constantly talking with the server, but in that case websockets are a better solution http://www.html5rocks.com/en/tutorials/websockets/basics/
Web workers are only supported on IE10+ so you will still need a fall back solution if you want to support older versions of IE. http://msdn.microsoft.com/en-us/library/ie/hh673568(v=vs.85).aspx
I have recently heard about the Web Workers spec that defines API for multi-threading JavaScript. But after working with client side scripting for so long now (and event-driven paradigm), I don't really see a point with using multiple thread.
I can see how the JavaScript engine and browser rendering engine can benefit from multi-threading, but I really don't see much benefit in handing this power to application programmers.
The Wikipedia article actually answers your question fairly well.
The power is given to us developers so that we can specifically offload tasks that would be disruptive to users to a web worker. The browser does not know which scripts are necessary for your custom interface to function properly, but you do.
If you've got a script that blocks the page rendering for 10 seconds but isn't necessary for the website to function, you could offload it to a web worker. Doing so allows your users to interact with the page instead of forcing them to wait 10 seconds for that script to execute. In a way, it's like AJAX in that things can be injected in after the interface loads so as to not delay users' interaction.
Is it possible utilize javascript in the making of windows desktop applications.I use borland delphi and i need to use javascript in my grids.
Worm, I've written a complete solution for you. See the screenshot attached below ...
A basic summary of what I can give is this ... a component that allows you to execute javascript, call delphi from from javascript, and access javascript functions and objects once you connect a script.
Here is a link to an brief article I wrote describing what you can do with javascript. At the end of the article is a zip file containing the source code and a compiled example program you can use to test out whatever javascript you want to write.
AJAX is a technology commonly applied in web applications where javascript is being executed by the client. Such notions are very difficult to apply in desktop applications. You could use background threads to perform expensive tasks to avoid freezing the application and then update the UI with the results of this background tasks.
Thanks a lot sysrpl.
This solution based on ActiveX and Internet Explorer. Required to write too much additional code for each JavaScript function/fearture you going to use.
I strongly suggest take a look on SpiderMonkey (Firefox) javascript wrapper. It's ready for RTTI.
http://code.google.com/p/delphi-javascript/
Required only 1 DLL. Compatible with XE2/XE4/XE5. Ready for x86 and x64 systems.
You can use one of JavaScript interpreters that are available on the market. First of all it's Windows Scripting Engine itself, that offers JScript (delphi wrapper would be needed for comfortable work). Next, it's FastScript by FastReports. There are more available, but I don't remember the names at the moment.
The problem, though, is that the language itself is not enough. What you seem to want is to use JavaScript code which makes use of HTML DOM and various browser classes. Obviously they are not available unless you have a browser engine itself in your program. I.e. if you embed TWebBrowser or link to Mozilla engine, you get the browser and you can run scripts inside of the browser window.
But if you want to automate Delphi GUI with JavaScript, this is probably not the best idea - browser-located JavaScript code will be useless for this.