How to calculate page loading time?

I am creating a function that calculates a page loading time. However, I am currently stuck in 2 issues:

  • When does the page finish creating HTML?
  • When does the page complete downloading all resources on the page (image, etc …)?
    Can anyone give me advice?