Js как перезагрузить страницу

от admin

Перезагрузка страницы на Javascript

Рассмотрим разные способы перезагрузки страницы. Для наглядности приведем готовые примеры.

Перезагрузка страницы в JS

За перезагрузку страниц в JS отвечает метод location.reload(). Он обновляет вкладку браузера и работает как при нажатии кнопки «Обновить страницу».

Пример перезагрузки страницы кликом на кнопку или ссылку:

Перезагрузка страницы с задержкой

В коде прописывается тот же location.reload() выполняемый с задержкой setTimeout() в 2 секунды.

<ahref=»#»onclick=»reload_interval(2000); return false;»>Обновить страницу через 2 секунды</a>

<script>
functionreload_interval(time) <
setTimeout(function() <
location.reload();
>, time);
>
</script>

Перезагрузка страницы с подтверждением

Чтобы пользователь мог подтвердить действие, можно использовать метод вызова диалогового сообщения:

confirm.
if (confirm(‘Вы действительно хотите обновить страницу?’)) <
window.location.reload();
>

Или по клику на ссылку:

<ahref=»#»onclick=»reload_confirm(); return false;»>Обновить страницу</a>

<script>
functionreload_confirm() <
if (confirm(‘Вы действительно хотите обновить страницу?’)) <
window.location.reload();
>
>
</script>

Пример:

Обновление родительской страницы из IFrame. Для обращения к ресурсам родительской страницы из IFrame применяется объект parent.

parent.location.reload();

<ahref=»#»onclick=»parent.location.reload(); return false;»>Обновить родительскую страницу</a>

Перезагрузка страницы с помощью HTML

Добавление мета-тега <metahttp-equiv=»refresh» content=»0″> в <head> страницы заставит её перезагрузиться. Значение атрибута content больше 0 задает задержку в секундах.

Перезагрузка страницы из PHP

Обновить страницу с сервера можно c помощью функции header(), отправив заголовок «Refresh: 5» (интервал в 5 секунд).

Внимание! Перед вызовом функции не должно быть отправки контента в браузер, к примеру, echo.

Refresh the Page in JavaScript – JS Reload Window Tutorial

Joel Olawanle

Refresh the Page in JavaScript – JS Reload Window Tutorial

When you’re developing applications like a blog or a page where the data may change based on user actions, you’ll want that page to refresh frequently.

When the page refreshes or reloads, it will show any new data based off those user interactions. Good news – you can implement this type of functionality in JavaScript with a single line of code.

In this article, we will learn how to reload a webpage in JavaScript, as well as see some other situations where we might want to implement these reloads and how to do so.

Here’s an Interactive Scrim about How to Refesh the Page in JavaScript

How to Refresh a Page in JavaScript With location.reload()

You can use the location.reload() JavaScript method to reload the current URL. This method functions similarly to the browser’s Refresh button.

The reload() method is the main method responsible for page reloading. On the other hand, location is an interface that represents the actual location (URL) of the object it is linked to – in this case the URL of the page we want to reload. It can be accessed via either document.location or window.location .

The following is the syntax for reloading a page:

Note: When you read through some resources on “page reload in JavaScript”, you’ll come across various explanations stating that the relaod method takes in boolean values as parameters and that the location.reload(true) helps force-reload so as to bypass its cache. But this isn’t the case.

According to the MDN Documentation, a boolean parameter is not part of the current specification for location.reload() — and in fact has never been part of any specification for location.reload() ever published.

Browsers such as Firefox, on the other hand, support the use of a non-standard boolean parameter known as forceGet for location.reload() , which instructs Firefox to bypass its cache and force-reload the current document.

Aside from Firefox, any parameters you specify in a location.reload() call in other browsers will be ignored and have no effect.

How to Perform Page Reload/Refresh in JavaScript When a Button is Clicked

So far we have seen how reload works in JavaScript. Now let’s now see how you can implement this could when an event occurs or when an action like a button click occurs:

Note: This works similarly to when we use document.location.reload() .

How to Refresh/Reload a Page Automatically in JavaScript

We can also allow a page refersh after a fixed time use the setTimeOut() method as seen below:

Using the code above our web page will reload every 3 seconds.

So far, we’ve seen how to use the reload method in our HTML file when we attach it to specific events, as well as in our JavaScript file.

How to Refresh/Reload a Page Using the History Function in JavaScript

The History function is another method for refreshing a page. The history function is used as usual to navigate back or forward by passing in either a positive or negative value.

For example, if we want to go back in time, we will use:

This will load the page and take us to the previous page we navigated to. But if we only want to refresh the current page, we can do so by not passing any parameters or by passing 0 (a neutral value):

Note: This also works the same way as we added the reload() method to the setTimeOut() method and the click event in HTML.

Wrapping Up

In this article, we learned how to refresh a page using JavaScript. We also clarified a common misconception that leads to people passing boolean parameters into the reload() method.

Обновить страницу с помощью JS / HTML / PHP

JS -метод location.reload() перезагружает текущую вкладку браузера и действует также как кнопка «Обновить страницу».

Пример перезагрузки страницы кликом на ссылку или кнопку:

Цикличное обновление страницы с задержкой

В коде используется тот же location.reload() выполняемый с задержкой setTimeout() в тридцать секунд.

Перезагрузка страницы с задержкой

В случаях когда после клика на кнопку или ссылку нужно перезагрузить страницу с задержкой, например две секунды:

Читать:
Как изменить курсор в фотошопе с крестика на кружок
Пример:

Перезагрузка страницы с подтверждением

Чтобы пользователь мог подтвердить действие, можно применить метод вызова диалогового сообщения confirm.

Или по клику на ссылку:

Пример:

Обновление родительской страницы из IFrame

Для обращения к ресурсам родительской страницы из IFrame используется объект parent , подробнее в статье «Как обновить iframe».

Перезагрузка страницы с помощью HTML

Добавление мета-тега <meta http-equiv="refresh" content="0"> в <head> страницы заставит её перезагрузится. Значение атрибута content больше нуля задает задержку в секундах.

Перезагрузка страницы из PHP

Обновить страницу прямо с сервера можно c помощью функции header() , отправив заголовок « Refresh: 5 », где значение «5» указывает интервал в пять секунд.

Важно, чтобы перед вызовом функции не было отправки контента в браузер, например echo .

How do I refresh a page using JavaScript?

Mateen Ulhaq's user avatar

For example, to reload whenever an element with id="something" is clicked:

The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false , so by default the page may reload from the browser’s cache.

Mateen Ulhaq's user avatar

Roy's user avatar

There are multiple unlimited ways to refresh a page with JavaScript:

  1. location.reload()
  2. history.go(0)
  3. location.href = location.href
  4. location.href = location.pathname
  5. location.replace(location.pathname)

If we needed to pull the document from the web-server again (such as where the document contents change dynamically) we would pass the argument as true .

You can continue the list being creative:

  • window.location = window.location
  • window.self.window.self.window.window.location = window.location

Mateen Ulhaq's user avatar

Thorben's user avatar

Lots of ways will work, I suppose:

  • window.location.reload();
  • history.go(0);
  • window.location.href=window.location.href;

Naveed's user avatar

David's user avatar

If you’re using jQuery and you want to refresh the contents of a page asynchronously, then you can do the following:

The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is "" , which means this page.

Note that this may not be what the asker meant by "refresh". Generally, in common usage, that term refers to reloading the page in the way that the browser would do if the user clicked the "Refresh/reload" button provided in the browser’s user interface. However, this is not the only possible meaning of "refresh", and it may be preferred in a specific circumstance.

What this code does is get new and updated content to the page. It does this by making an asynchronous HTTP request for the new content, and then replacing the page’s current content with the new asynchronously-loaded content. It has the result of refreshing the contents of the page, even though it works slightly differently.

You’ll have to choose which one you actually want, and which works best for your specific use-case.

Peter's user avatar

If the current page was loaded by a POST request, you may want to use

because window.location.reload() will prompt for confirmation if called on a page that was loaded by a POST request.

Mark Amery's user avatar

You’re spoiled for choice; any of the following work:

  • window.location.href = window.location.href;
  • window.location.reload();
  • history.go(0);

You may want to use

forceGet is a boolean and optional.

The default is false which reloads the page from the cache.

Set this parameter to true if you want to force the browser to get the page from the server to get rid of the cache as well.

if you want quick and easy with caching.

Peter Mortensen's user avatar

Pinch's user avatar

Three approaches with different cache-related behaviours:

location.reload(true)

In browsers that implement the forcedReload parameter of location.reload() , reloads by fetching a fresh copy of the page and all of its resources (scripts, stylesheets, images, etc.). Will not serve any resources from the cache — gets fresh copies from the server without sending any if-modified-since or if-none-match headers in the request.

Equivalent to the user doing a "hard reload" in browsers where that’s possible.

Note that passing true to location.reload() is supported in Firefox (see MDN) and Internet Explorer (see MSDN) but is not supported universally and is not part of the W3 HTML 5 spec, nor the W3 draft HTML 5.1 spec, nor the WHATWG HTML Living Standard.

In unsupporting browsers, like Google Chrome, location.reload(true) behaves the same as location.reload() .

location.reload() or location.reload(false)

Reloads the page, fetching a fresh, non-cached copy of the page HTML itself, and performing RFC 7234 revalidation requests for any resources (like scripts) that the browser has cached, even if they are fresh are RFC 7234 permits the browser to serve them without revalidation.

Exactly how the browser should utilise its cache when performing a location.reload() call isn’t specified or documented as far as I can tell; I determined the behaviour above by experimentation.

This is equivalent to the user simply pressing the "refresh" button in their browser.

location = location (or infinitely many other possible techniques that involve assigning to location or to its properties)

Only works if the page’s URL doesn’t contain a fragid/hashbang!

Reloads the page without refetching or revalidating any fresh resources from the cache. If the page’s HTML itself is fresh, this will reload the page without performing any HTTP requests at all.

This is equivalent (from a caching perspective) to the user opening the page in a new tab.

However, if the page’s URL contains a hash, this will have no effect.

Again, the caching behaviour here is unspecified as far as I know; I determined it by testing.

Похожие статьи