In javascript, I want to execute an action if the current thread is already a non-main thread, or pass it off to a non-main thread if the current thread is the main.
To this end, how can I test if the current thread is the main thread or a non-main thread?
If I call the jquery method $.get()
the OnSuccess event is run on the non-main thread. I can achieve the pass-off simply by invoking $.get()
on a do-nothing URL.
Why do I need to do this? There are some javascript calls that cause an ugly warning if called on the main thread. I would like to avoid this warning. The warning is ...
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
function doOnNonMainThread( action) {
if (thisIsANonMainThread()) {
$.get( 'some-url', action, 'xml');
} else {
action();
}
}
I am invoking the Saxon-JS library (XPath evaluate function). This library in turn invokes synchronous XMLHttpRequest. I can't modify the XPath library, I have to use it as is. There are places where I call XPath from within an Ajax success event. In this case, I get no warning - all good so far. There are places where I call XPath NOT within an Ajax response event. In these cases, I get the warning.
Some answerers have suggested that I just dont call synchronous XMLHttpRequest. This is not a viable solution, as I don't control the Saxon-JS library. All I can control is the context from which I call the Saxon-JS library.
Saxon-JS will only use synchronous calls on XMLHttpRequest if your XSLT stylesheet (or a dynamically-evaluated XPath expression) makes calls on functions such as doc() or document(). Saxon-JS provides alternatives to these constructs, by using the ixsl:schedule-action instruction to make an asynchronous request. Unfortunately, the fact that you aren't using the functions that trigger a synchronous request doesn't prevent the browser issuing this warning. I don't know any way to prevent the warning, but you should be able to safely ignore it.
PS: Just been discussing this with my colleagues. There may still be some cases where Saxon-JS makes synchronous requests for other resources, such as the Unicode character tables used for evaluating some regular expressions. We will investigate further. Please raise an issue on the Saxon-JS project at saxonica.plan.io so we can track this to a resolution.