zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Order of execution for ajax and js events

There is a requirement to execute the current animation when scrolling to the corresponding position using the scroll wheel. This animation is inside the footer, while the main body of the webpage is rendered using ajax. I call ajax to render the data in JavaScript, and then get the height of the main body. When scrolling to that height, the animation is executed.

I tested it locally and there were no issues, all the expected effects were present. However, when testing it on the server, no matter how I wrote the code, it always obtained the height of the main body first and then rendered the data. Therefore, the height was always a very small value, which did not meet my desired attribute.

I roughly came up with two solutions, but both ended in failure. Locally, ajax is executed first, while on the server, JavaScript is executed first.

  1. Delay the event of obtaining the height by 500ms, but found that the event cannot be obtained in the end.
  2. Write the event inside the success callback of ajax. The result is that it only works the first time the webpage is opened, and no matter how many times it is refreshed, it is ineffective. The event is blocked, so method two is also discarded.

Finally, I thought of it. Isn't ajax an asynchronous method? If I change it to synchronous, then ajax will be executed first before the JavaScript event.

async: false,

I added async in ajax, and set it to false, which means it is set to synchronous data retrieval. Great! I went back to the server and opened the console, and found that the data was rendered first before obtaining the height of the main body. The problem was solved.

Of course, there are drawbacks to doing this. If the interface has a problem and ajax rendering fails, then the entire webpage's JavaScript will not be executed. However, I think if the data cannot be rendered, there is no point in accessing the webpage, so in the end, I adopted this method.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.