There is a requirement to execute the current animation when scrolling to the corresponding position using the scroll wheel. This animation is located in the footer
, while the main content of the webpage is rendered using ajax
. I call ajax to render the data in JavaScript, and then obtain the height of the main content. When scrolling to that height, the animation is executed.
I tested it locally and there were no issues, and all the expected effects were present. However, when testing it on the server, regardless of how it was written, the height of the main content was always obtained before rendering the data. Therefore, the height was inevitably a very small value, which did not meet the desired attribute.
I roughly thought of two solutions, but both ended in failure. Locally, ajax is executed first, while on the server, JavaScript is executed first.
- Delay the event for obtaining the height by 500ms, but found that the event could not be obtained at the end.
- 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 becomes ineffective. The event is blocked, so method two is also abandoned.
Finally, I came up with the idea that ajax is an asynchronous method. If I change it to synchronous, then ajax will be executed first before the JavaScript event.
async: false,
I added the async
method in ajax, and set it to false
, which means that 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 content. The problem was resolved.
Of course, there are drawbacks to doing this. If the interface has issues and the 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.