Программирование

Как менять заголовок страницы динамически с JavaScript

Узнайте, как мгновенно менять document.title при переключении вкладок в SPA, используя History API и JavaScript, чтобы URL оставался SEO‑дружелюбным и совместимым с соцсетями.

We accidentally wrote a huge nonsense. We need to produce the correct translation. Let’s produce the translation.Как можно динамически менять заголовок страницы на лету с помощью JavaScript, когда переключаюсь между вкладками, без перезагрузки? У меня клиентский интерфейс с вкладками, и для SEO я хочу, чтобы заголовок документа соответствовал активной вкладке. Какой подход в JavaScript позволит это сделать?

The page title can be updated on the fly simply by assigning a new string to document.title.
When you click a tab, run a handler that sets the title and optionally updates the browser history with history.replaceState so the URL stays the same and no reload occurs.
For SEO‑friendly tabs you can also push a new state with history.pushState to make each tab shareable while ensuring the title matches the content.

Обновление document.title при переключении вкладок

When a tab becomes active you can set the document title directly:

javascript
function activateTab(tab) {
  // tab.title contains the desired title
  document.title = tab.title;
}

This assignment happens instantly, no reload needed, and works across all modern browsers.
MDN Web Docs – document.title tells you you can read or modify the title anytime after the page loads.

Tip: Keep the title concise—50 to 60 characters—so it shows up fully in search results.
Best practice: Use the same title that appears in the tab’s content; it keeps things consistent for users and search engines.


Использование History API для управления URL

If you want each tab to be linkable and shareable, you can update the URL without reloading the page:

javascript
function activateTab(tab) {
  document.title = tab.title;
  const url = new URL(window.location);
  url.searchParams.set('tab', tab.id);           // e.g., ?tab=blog
  history.replaceState({ tab: tab.id }, '', url);
}
  • history.replaceState updates the current entry, keeping the back button’s behavior natural.
  • history.pushState adds a new entry if you want the tab change to be history‑able.

MDN’s History API page gives a detailed look at how to use pushState, replaceState, and popstate events.


SEO‑связанные соображения для клиент‑сайд интерфейсов

Search engines are getting better at indexing JavaScript‑generated content, but it’s still good to give clear signals:

  1. Dynamic titles – As shown above, match each tab’s content with its title.
  2. Meta tags – Update <meta name="description"> with the active tab’s description if it differs.
  3. Structured data – Consider adding JSON‑LD that reflects the active content.
  4. Server‑side fallback – For crawlers that don’t execute JavaScript, serve a static fallback page for each tab or use prerendering.

Google’s Search Central blog explains how dynamic titles affect indexing: Managing page titles.
For detailed guidance on client‑side rendering and SEO, see the Google Search Central – Structured data & dynamic pages article.


Пример реализации

Below is a minimal, self‑contained example that ties everything together:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Home</title>
  <style>
    .tab { cursor: pointer; padding: 0.5rem; }
    .active { font-weight: bold; }
  </style>
</head>
<body>
  <nav id="tabs">
    <span data-id="home" data-title="Home" class="tab active">Home</span>
    <span data-id="blog" data-title="Blog" class="tab">Blog</span>
    <span data-id="contact" data-title="Contact Us" class="tab">Contact</span>
  </nav>
  <section id="content">
    <h1 id="heading">Home</h1>
    <p id="text">Welcome to the home page.</p>
  </section>

  <script>
    const tabs = document.querySelectorAll('#tabs .tab');
    const heading = document.getElementById('heading');
    const text = document.getElementById('text');

    tabs.forEach(tab => {
      tab.addEventListener('click', () => {
        // Удаляем класс active со всех вкладок
        tabs.forEach(t => t.classList.remove('active'));
        tab.classList.add('active');

        // Обновляем заголовок
        document.title = tab.dataset.title;

        // Обновляем содержимое (простая демонстрация)
        heading.textContent = tab.dataset.title;
        text.textContent = `This is the ${tab.dataset.title.toLowerCase()} page.`;

        // Обновляем URL без перезагрузки
        const url = new URL(window.location);
        url.searchParams.set('tab', tab.dataset.id);
        history.replaceState({ tab: tab.dataset.id }, '', url);
      });
    });
  </script>
</body>
</html>

Clicking a tab changes the page title, updates the displayed content, and modifies the URL—all without a page reload.


Заключение

  • Прямое присваивание (document.title = '…') — самый простой способ мгновенно изменить заголовок.
  • API истории (replaceState или pushState) синхронизирует URL с активной вкладкой, повышая удобство обмена и навигацию.
  • SEO: синхронизируйте заголовки, мета‑описания и структурированные данные с содержимым активной вкладки; рассмотрите серверный рендеринг или prerendering для роботов, которые не исполняют JavaScript.
  • Реализуйте небольшую функцию‑обработчик клика, которая обновляет заголовок, содержимое и URL в одном месте, обеспечивая плавный, SEO‑дружественный интерфейс вкладок.
Авторы
Проверено модерацией
Модерация