How to disable the automatic scroll of browser on back navigation

I have a Product Listing Page and Product Detail Page. The products in PLP are listed dynamically through graphql. The scenario is when a product is clicked on the PLP it takes me to PDP and when browser’s back button is clicked, it takes me back to PLP. Now, as we know browsers have default scroll set for back navigation to that part of the page till where it was last scrolled to. So, same is happening here, when I click on back button from PDP and it lands on PLP,the page is landed on the part where it was last scrolled to but in some cases where internet is slow and there is no html as data is dynamic, it slides to the bottom, i.e., footer and then it has to be manually scrolled to the product DOM. I tried to disable the automatic scroll for the PDP click scenario using the below code:

if ('scrollRestoration' in history) {
    history.scrollRestoration = 'auto';
}

This works if I run this directly without any condition. But for my case, I have added the Product Id of the product which is clicked on the page in Session Storage. So, I need to check that variable if it exists in session storage, if yes then only the above code will run. So, the getting of session storage takes time and browser already initiates the auto scroll. Below is the code:

if(!sessionStorage.getItem("productId")){
  if ('scrollRestoration' in history) {
      history.scrollRestoration = 'auto';
  }
}

Is there any way I can run this code first when the page is loading. I have tried document ready but also not working. Anything which can work just when page is landed, even before html is rendered?