Dynamic Meta Tag Updates
You'll learn how to change page titles and meta tags in JavaScript-driven single-page applications when users navigate between routes.
Why This Matters in SPAs
In traditional multi-page websites, each new page load brings fresh HTML with its own <title> and meta tags. But in single-page applications (SPAs), you navigate between "pages" without full page reloads—the JavaScript changes the content, but the original HTML head stays the same. This creates an SEO and user experience problem: the browser tab still shows the homepage title, and social media crawlers see outdated meta descriptions.
How to Update Meta Tags with JavaScript
You can dynamically update meta tags using the DOM:
// Update the page title
document.title = "About Us - My SPA";
// Update meta description
const metaDescription = document.querySelector('meta[name="description"]');
if (metaDescription) {
metaDescription.setAttribute('content', 'Learn about our mission and team.');
}
// Update Open Graph tags
const ogTitle = document.querySelector('meta[property="og:title"]');
if (ogTitle) {
ogTitle.setAttribute('content', 'About Us - My SPA');
}
When to Trigger Updates
Call these updates whenever your SPA's route changes—typically in your router's navigation handler or in a component that mounts for each route.
function navigateToAbout() {
// Update URL and content
history.pushState({}, '', '/about');
// Update meta tags
document.title = "About Us - My SPA";
updateMetaTag('description', 'Learn about our mission and team.');
}
function updateMetaTag(name, content) {
const meta = document.querySelector(`meta[name="${name}"]`);
if (meta) meta.setAttribute('content', content);
}
Key Takeaway: In single-page applications, you must manually update document.title and meta tag content attributes via JavaScript during route changes to maintain proper SEO and user experience across "pages."