Javascript this location reload

Window location.reload()

The reload() method does the same as the reload button in your browser.

Syntax

Parameters

Return Value

Browser Support

location.reload() is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Читайте также:  Cheat sheet for html

Источник

window . location

location — это объект хранящийся в window , который позволяет получать информацию о текущем адресе страницы и менять его с помощью функций или обновления полей объекта.

Пример

Скопировать ссылку «Пример» Скопировано

С помощью location мы можем получить текущий адрес:

 // если выполнить этот скрипт на текущей странице доки в консолиconsole.log(window.location.href)// 'https://doka.guide/js/window-location/' // если выполнить этот скрипт на текущей странице доки в консоли console.log(window.location.href) // 'https://doka.guide/js/window-location/'      

Обновление текущей страницы можно произвести с помощью reload ( ) . Этот метод делает то же самое, что и кнопка «Обновить» в браузере:

 window.location.reload() window.location.reload()      

С помощью replace ( ) можно сделать клиентский редирект, это приведёт к мгновенному переходу по адресу, указанному при вызове метода:

 window.location.replace('https://doka.guide/') window.location.replace('https://doka.guide/')      

Как понять

Скопировать ссылку «Как понять» Скопировано

Для навигации по сайту мы используем адреса и параметры страницы. window . location содержит набор свойств и методов, чтобы удобно получать адрес и управлять им.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Свойства

Скопировать ссылку «Свойства» Скопировано

Ссылка, на которой обозначены все свойства window.location

href – полное представление адреса. Можно сказать, что это зеркало того, что находится в адресной строке браузера в данный момент. Если записать значение в это свойство, то произойдёт обновление адреса и редирект на новый адрес.

Остальные свойства — это кусочки location . href . Они нужны, чтобы удобно получать каждый из них отдельно, а не вытаскивать их руками из полной строки адреса.

 console.log(window.location.href)// отобразит текущий адресwindow.location.href = 'https://example.com'// сделает переход по указанному адресу console.log(window.location.href) // отобразит текущий адрес window.location.href = 'https://example.com' // сделает переход по указанному адресу      

protocol содержит текущий протокол по которому открыта страница. Чаще всего там будет https и http .

host содержит значение хоста из ссылки. Хост включает в себя название текущего домена и порта.

hostname — частичка с доменом из свойства host , не включает в себя порт.

port — вторая составляющая значения host , содержит только номер порта. Если порт не указан в явном виде, то значением свойства будет пустая строка » .

origin включает в себя путь, начиная с protocol и заканчивая port .

search содержит параметры в формате ключ = значение разделённые & . Если параметров нет, то значением будет пустая строка.

hash — якорная ссылка включая символ # . Она находится в самом конце пути и отвечает за навигацию между размеченными на странице элементами с помощью установки атрибута id на тегах. Эта часть URL не передаётся на сервер. Если параметров нет, то значением будет пустая строка.

 window.location.hash = 'в-работе'// проскролит страницу до элемента с `id="в-работе"` если такой присутствует на страницеconsole.log(window.location.hash)// напечатает якорь window.location.hash = 'в-работе' // проскролит страницу до элемента с `id="в-работе"` если такой присутствует на странице console.log(window.location.hash) // напечатает якорь      

pathname – репрезентация текущего пути на сайте. Если текущий урл не содержит путь, то значением будет корневой путь » / » .

Например, значения window . location . pathname в зависимости от адреса:

  • https : / / doka . guide / js / window — location / → /js / window — location / .
  • https : / / doka . guide → / .

Методы

Скопировать ссылку «Методы» Скопировано

assign ( новый _ путь ) – метод вызывает переход на страницу, переданную в аргументах. После перехода на страницу пользователь может вернуться на страницу, с которой произошёл переход, с помощью браузерной кнопки назад.

replace ( новый _ путь ) аналогичен методу assign ( ) , но адрес страницы с которой был вызван этот метод не будет сохранён в истории браузера. При попытке вернуться назад пользователь будет отправлен на страницу предшествующую той, с которой произошёл переход.

reload ( ) перезагружает текущую страницу.

to String ( ) приводит адрес страницы к строке. Возвращает то же самое значение, что и location . href .

Источник

JavaScript Refresh Page – How to Reload a Page in JS

Joel Olawanle

Joel Olawanle

JavaScript Refresh Page – How to Reload a Page in JS

JavaScript is a versatile programming language that allows developers to create dynamic and interactive web applications. One common task in web development is to refresh or reload a web page, either to update its content or to trigger certain actions.

In this article, we will explore different ways to refresh a page in JavaScript and understand the pros and cons of each approach.

Why Refresh a Page in JavaScript?

Refreshing a web page can be useful in various scenarios. For example:

  1. Content Update: If the content on a web page is dynamic and changes frequently, you may need to refresh the page to display the latest data or information. This is commonly seen in news websites, stock market trackers, weather apps, and so on.
  2. Form Submission: After submitting a form on a web page, you may want to refresh the page to show a success message or reset the form for a new submission.
  3. State Reset: In some cases, you may want to reset the state of a web page or clear certain data to start fresh. Refreshing the page can help achieve this.

Now, let’s explore different ways to refresh a page in JavaScript.

Method 1: How to Refresh the Page Using location.reload()

The simplest way to refresh a page in JavaScript is to use the location.reload() method. This method reloads the current web page from the server, discarding the current content and loading the latest content.

// Refresh the page location.reload(); 

Pros of Using location.reload()

  • It’s straightforward and easy to use.
  • It reloads the entire page from the server, ensuring that you get the latest content.

Cons of Using location.reload()

  • It discards the current content of the page, which can result in loss of user input or data.
  • It may cause a flickering effect as the page reloads, which can impact user experience.

Method 2: How to Refresh the Page Using location.replace()

Another way to refresh a page in JavaScript is to use the location.replace() method. This method replaces the current URL of the web page with a new URL, effectively reloading the page with the new content.

When you try this in your console, you will notice it displays your current URL:

This means, when you use the location.replace() method to replace the current URL of the web page with a new URL (same URL), your page will refresh.

// Refresh the page by replacing the URL with itself location.replace(location.href); 

Pros of Using location.replace()

  • It’s a quick way to reload the page with new content.
  • It preserves the current content of the page and replaces only the URL, avoiding loss of user input or data.

Cons of Using location.replace()

  • It replaces the entire URL of the page, which may result in the loss of the current browsing history.
  • It may not work in some scenarios, such as when the web page was opened in a new window or tab.

Method 3: How to Refresh the Page Using location.reload(true)

The location.reload() method also accepts a boolean parameter forceGet which, when set to true , forces the web page to reload from the server, bypassing the cache.

This can be useful when you want to ensure that you get the latest content from the server, even if the page is cached.

// Refresh the page and bypass the cache location.reload(true); 

Pros of Using location.reload(true)

Cons of Using location.reload(true)

  • It discards the current content of the page, which can result in loss of user input or data.
  • It may cause a flickering effect as the page reloads, which can impact user experience.

Method 4: How to Refresh the Page Using location.href

Another way to refresh a page in JavaScript is to use the location.href property to set the URL of the web page to itself. This effectively reloads the page with the new URL, triggering a page refresh.

// Refresh the page by setting the URL to itself location.href = location.href; 

Pros of Using location.href

  • It’s a simple and effective way to refresh the page.
  • It preserves the current content of the page and only updates the URL, avoiding loss of user input or data.

Cons of Using location.href

  • It replaces the entire URL of the page, which may result in the loss of the current browsing history.
  • It may not work in some scenarios, such as when the web page was opened in a new window or tab.

Method 5: How to Refresh the Page Using location.reload() with a Delay

If you want to add a delay before refreshing the page, you can use the setTimeout() function in combination with the location.reload() method.

This allows you to specify a time interval in milliseconds before the page is reloaded, giving you control over the timing of the refresh.

// Refresh the page after a delay of 3 seconds setTimeout(function()< location.reload(); >, 3000); // 3000 milliseconds = 3 seconds 

Pros of Using location.reload() with a Delay

  • It allows you to control the timing of the page refresh by adding a delay.
  • It provides flexibility in scenarios where you want to refresh the page after a certain event or action.

Cons of Using location.reload() with a Delay

  • It may cause a delay in the page refresh, which can impact user experience.
  • It may not work as expected in scenarios with unstable or slow network connections.

Wrapping Up

In this article, you have learned the different ways to refresh a page in JavaScript. Each method has its pros and cons, which should make it easier for you to choose the best method for your web development project.

When using any of these methods to refresh a page, it’s important to consider the impact on user experience, data loss, and browsing history.

I hope this article helps you understand how to reload a web page in JavaScript and choose the appropriate method for your specific use case.

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

Источник

Оцените статью