Are there any best practices for maintaining the scroll position of a div after refreshing the page in PHP?

When a page is refreshed, the scroll position of a div is typically lost. To maintain the scroll position after refreshing the page, you can use JavaScript to store the scroll position in a cookie before the page is refreshed and then retrieve it after the page reloads.

<?php
// Check if the scroll position is set in a cookie
if(isset($_COOKIE['scroll_position'])){
    echo '<script>window.onload = function() { window.scrollTo(0, '.$_COOKIE['scroll_position'].'); }</script>';
}

// Set the scroll position in a cookie before refreshing the page
echo '<script>window.onbeforeunload = function() { document.cookie = "scroll_position=" + window.scrollY; }</script>';
?>