Imagine you need a page that always reloads itself from the server when the user focuses it, that means the according browser tab or window was in background and gets clicked to foreground. For such a page the user would never have to press the "Reload" button when coming back to it, which may make sense e.g. for a wheather-report site (to always show the current temperature).
This is different from updating the page periodically, which can be done via therefresh
attribute in a<head> <meta>
element. Mind that such would take control away from the user, may consume valuable resources, and is not applicable in all environments.
Code
Following HTML would do a page reload on focus. Mind that this is not recommendable for big expensive pages that need several seconds to render!
<!DOCTYPE HTML> <html> <body onfocus="window.location = window.location;"> <!-- Here goes the page HTML --> </body> </html>
The technique is to install an event handler for the focus event in the <body>
element.
The JavaScript code "window.location = window.location;"
inside the event handler may look ridiculous, but it actually performs a page reload.
Test
Here is a test-page to verify that behavior. It displays the current time every time it gets loaded, and it has the above mechanism installed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE HTML> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Show Load Time when Focused</title> </head> <body onpageshow="renderTime();" onfocus="window.location = window.location;" > <fieldset> <legend>Load Time:</legend> <div id="time"></div> </fieldset> <script> function renderTime() { const date = new Date(); const timeField = document.getElementById("time"); timeField.innerHTML = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); } </script> </body> </html> |
To verify,
- load this page in your web-browser,
- look at the displayed time, remember it,
- then open a new tab or window and focus it (or click onto some already opened),
- then change back to this page
→ The displayed time must have changed now.
Resume
I do not know if this is the simplest way to make a page reload itself automatically when it is looked at, but at least it needs very few code. If you need to update just single elements or fields on focus, you will have to use AJAX.
Keine Kommentare:
Kommentar veröffentlichen