How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

后端 未结 14 2297
暗喜
暗喜 2020-11-21 05:07

I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an

14条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 05:54

    Note: You shouldn't use async: false due to this warning messages:

    Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

    Chrome even warns about this in the console:

    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/.

    This could break your page if you are doing something like this since it could stop working any day.

    If you want to do it a way that still feels like if it's synchronous but still don't block then you should use async/await and probably also some ajax that is based on promises like the new Fetch API

    async function foo() {
      var res = await fetch(url)
      console.log(res.ok)
      var json = await res.json()
      console.log(json)
    }
    

    Edit chrome is working on Disallowing sync XHR in page dismissal when the page is being navigated away or closed by the user. This involves beforeunload, unload, pagehide and visibilitychange.

    if this is your use case then you might want to have a look at navigator.sendBeacon instead

    It is also possible for the page to disable sync req with either http headers or iframe's allow attribute

提交回复
热议问题