Кнопка обновить страницу javascript

How do I refresh a page using JavaScript?

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.

This didn’t work for me. window.location.href=window.location.href; and location.href=location.href; worked.

The extra argument in location.reload(true) is not standard but most browsers support it. Some discussion and history in MDN documentation. «. has never been part of any specification for location.reload() ever published»

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)
  6. location.reload(false)

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
  • . and other 534 ways
var methods = [ "location.reload()", "history.go(0)", "location.href = location.href", "location.href = location.pathname", "location.replace(location.pathname)", "location.reload(false)" ]; var $body = $("body"); for (var i = 0; i < methods.length; ++i) < (function(cMethod) < $body.append($("", < text: cMethod >).on("click", function() < eval(cMethod); // don't blame me for using eval >)); >)(methods[i]); >

+1 for the list and jsfiddle. I have a question, in jsfiddle 1 and 6 make the generated page to disappear for a moment as it being reloaded, and 2-5 make page reload being «unnoticeable». In dev tool in chrome I can see the page being regenerated, but could you explain the redrawing process being defferent? please. Thank you in advance.

1 and 6 (reload()/(false)) are slower. hmmm. interesting. 🙂 and 1 and 6 are the same as reload() ‘s default parameter is false .

Lots of ways will work, I suppose:

This window.location.href=window.location.href; will do nothing if your URL has a #/hashbang on the end example.com/something#blah :

In case anyone’s wondering what the difference between location.reload() and history.go(0) is: there is none. The relevant section of the HTML 5 spec at w3.org/TR/html5/browsers.html#dom-history-go explicitly dictates that they are equivalent: «When the go(delta) method is invoked, if the argument to the method was omitted or has the value zero, the user agent must act as if the location.reload() method was called instead.»

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.

Источник

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

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

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

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

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

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

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

 Обновить страницу через 2 секунды  

Пример:

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

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

if (confirm('Вы действительно хотите обновить страницу?'))

Пример:

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

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

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

Добавление мета-тега в страницы заставит её перезагрузится. Значение атрибута content больше нуля задает задержку в секундах.

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

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

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

Источник

Refresh the Page in JavaScript – JS Reload Window Tutorial

Joel Olawanle

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.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

How to reload a page using JavaScript

Some browsers support an optional boolean parameter that will forcibly clear the cache (similar to Ctrl+Shift+R), but this is nonstandard and poorly supported and documented and should generally not be used:

//Force a hard reload to clear the cache if supported by the browser window.location.reload(true); 

JavaScript 1.1

window.location.replace(window.location.pathname + window.location.search + window.location.hash); // does not create a history entry 

JavaScript 1.0

window.location.href = window.location.pathname + window.location.search + window.location.hash; // creates a history entry 

It looks like location.reload(forceReload: boolean) is deprecated now (just the true / false parameter), though it might still work.

As far as I know, it never was part of any specification. To force reloading (bypassing the cache), adding a random parameter which is not used otherwise to the URL as a dirty solution will work. Maybe something like nocache=’ + (new Date()).getTime() .

See this MDN page for more information.

If you are refreshing after an onclick then you’ll need to return false directly after

location.reload(); return false; 

@ShivanRaptor Usually none, in web browsers context, location is the same as window.location as window is the global object.

I prefer to use window.location.reload(); for readability, as location could be a local variable — whereas you’d usually avoid variables of the name window .

@Rimian — IMHO, return false; is not strictly necessary in a handler: doesn’t reload supersede any further processing?

I was looking for some information regarding reloads on pages retrieved with POST requests, such as after submitting a method=»post» form.

To reload the page keeping the POST data, use:

To reload the page discarding the POST data (perform a GET request), use:

window.location.href = window.location.href; 

Hopefully this can help others looking for the same information.

window.location.href = window.location.href does not reload the page if the current url contains a # . You could remove the hash if you don’t need it window.location.href = window.location.href.split(‘#’)[0]; .

You can perform this task using window.location.reload(); . As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation

JavaScript window.location object can be used

  • to get current page address (URL)
  • to redirect the browser to another page
  • to reload the same page

window : in JavaScript represents an open window in a browser.

location : in JavaScript holds information about current URL.

The location object is like a fragment of the window object and is called up through the window.location property.

location object has three methods:

  1. assign() : used to load a new document
  2. reload() : used to reload current document
  3. replace() : used to replace current document with a new one

So here we need to use reload() , because it can help us in reloading the same document.

So use it like window.location.reload(); .

To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload() . This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.

Источник

Читайте также:  Java браузер по умолчанию
Оцените статью