In certain web documents, retrieving the height using standard methods poses a challenge. This issue is further compounded by the inefficacy of padding the bottom of the document. Take, for instance, the websites fandango.com and paperbackswap.com:
On fandango.com:
On paperbackswap.com:
Document height calculation across browsers is a compatibility nightmare. While all browsers offer clientHeight and scrollHeight properties, they differ in their calculation methods.
Best Practice for Accurate Height Retrieval
The most reliable way to obtain the correct document height is to gather all height values from document or documentElement and utilize the highest one. This approach is essentially employed by jQuery:
var body = document.body, html = document.documentElement; var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
This method yields the correct height for both fandango.com and paperbackswap.com.
Cautions
Attempting to retrieve document height before the document is fully loaded will always result in 0. Additionally, dynamic content loading or window resizing may necessitate re-testing. Monitor these events and test accordingly.
The above is the detailed content of How Can I Reliably Determine the Height of a Web Document in JavaScript Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!