jquery force page to reload on viewport resize

How to Force a Page to Reload on Viewport Resize using jQuery

If you want to force a page to reload whenever the viewport is resized, jQuery provides a simple way to do that. This can be useful if your website layout changes significantly on different screen sizes and you want to ensure that the latest version of the page is always displayed.

Method 1: Using the location.reload() method

The easiest way to force a page to reload on viewport resize is by using the location.reload() method. This method reloads the current page from the server, which means that all scripts and stylesheets will also be reloaded. Here's an example:

$((window).on('resize', function() {
  location.reload();
});

In this example, we're using jQuery to attach a resize event listener to the window object. Whenever the window is resized, the location.reload() method is called, which reloads the page.

Method 2: Using the location.href property

If you prefer not to use the location.reload() method, you can also force a page to reload by setting the location.href property to the current URL. This has the same effect as clicking the reload button in the browser. Here's an example:

$((window).on('resize', function() {
  location.href = location.href;
});

In this example, we're using jQuery to attach a resize event listener to the window object. Whenever the window is resized, we're setting the location.href property to the current URL, which reloads the page.

Conclusion

Both of these methods are effective in forcing a page to reload on viewport resize. The location.reload() method is simpler to use, but it reloads all scripts and stylesheets, which can slow down your website. The location.href property is a bit more complex, but it only reloads the page without any additional resources. Choose the method that works best for your website.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe