<title> - Document title
The <title>
tag is an indispensable part of an HTML document, defining the text displayed in the browser tab or window title bar. Search engines also use this title as the link title in search results, making it crucial for SEO.
Basic Syntax of the <title>
Tag
The <title>
tag must be placed within the <head>
section, and each HTML document can have only one <title>
tag. The basic syntax is as follows:
<!DOCTYPE html>
<html>
<head>
<title>This is the page title</title>
</head>
<body>
<!-- Page content -->
</body>
</html>
This simple example demonstrates how to use the <title>
tag in an HTML document. The browser will display "This is the page title" as the page title.
Importance of the <title>
Tag
The <title>
tag plays a key role in several aspects:
- Browser Display: Appears in browser tabs, window title bars, and bookmarks.
- SEO Optimization: Search engines use the title as the primary link text in search results.
- User Experience: Helps users identify and distinguish between multiple open tabs.
- Social Media Sharing: Many social platforms prioritize the title text when sharing links.
Best Practices for the <title>
Tag
Length Control
The ideal title length is typically between 50-60 characters. Exceeding this length may cause search engines to truncate it. For example:
<title>How to Make a Delicious Chocolate Cake - Home Baking Guide</title>
This title includes the main content while staying within a reasonable length.
Content Structure
Good titles often follow a "Primary Content - Secondary Information" structure:
<title>HTML Tutorial: From Beginner to Pro | Programming Learning Site</title>
Keyword Optimization
Placing important keywords at the beginning of the title can improve SEO:
<title>JavaScript Closures Explained: Scope and Memory Management</title>
Dynamically Setting the <title>
For single-page applications (SPAs) or cases where the title needs to be changed dynamically, JavaScript can be used:
// Using vanilla JavaScript
document.title = "New Page Title";
// In React
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
document.title = "React App - User Dashboard";
}, []);
return <div>Content</div>;
}
// In Vue
export default {
mounted() {
document.title = "Vue App - Product List";
}
}
<title>
for Multilingual Sites
For multilingual websites, titles can be set dynamically based on the user's language:
<script>
const userLang = navigator.language || navigator.userLanguage;
if(userLang.startsWith('zh')) {
document.title = "Chinese Title";
} else {
document.title = "English Title";
}
</script>
<title>
and the Open Graph Protocol
When a webpage is shared on social media, the Open Graph protocol can override the <title>
:
<meta property="og:title" content="Different Title Displayed When Shared on Social Media">
Common Mistakes and How to Avoid Them
-
Forgetting to Add the
<title>
Tag:<!-- Bad Example --> <head> <meta charset="UTF-8"> </head>
-
Using Too Many Keywords in the
<title>
:<!-- Poor Example --> <title>Buy Phones, Smartphones, Cheap Phones, Latest Phones, Phone Deals</title>
-
Using the Same Title for All Pages:
<!-- Poor Example - All Pages --> <title>My Website</title>
Special Use Cases for the <title>
Tag
Status Notifications
Some websites display notification counts in the title:
function updateNotificationCount(count) {
document.title = count > 0
? `(${count}) My Inbox`
: "My Inbox";
}
Page Status Indicators
On form pages, you can prompt users about save status:
let isChanged = false;
form.addEventListener('input', () => {
isChanged = true;
document.title = (isChanged ? "* " : "") + "Edit Profile";
});
Browser Behavior with the <title>
Tag
Different browsers handle long titles slightly differently:
- Chrome and Firefox typically truncate after about 60 characters.
- Mobile devices have even more limited display space.
- Browser history and bookmarks may display the full title.
Testing titles of varying lengths is important:
<title>This is a very long title used to test how browsers truncate overly long title text and observe the display effect...</title>
<title>
and Accessibility
Screen readers read the page title first, so:
- Ensure the title accurately describes the page content.
- Avoid vague descriptions like "Homepage" or "New Page."
- For form submission result pages, reflect the status in the title.
<!-- After Form Submission -->
<title>Registration Successful - User Account Created</title>
Historical Evolution of the <title>
Tag
HTML specifications have kept the <title>
tag requirements stable:
- HTML 2.0 (1995): First standardized.
- HTML 4.01: Became a required element.
- XHTML: Must be properly closed.
- HTML5: Basic functionality remains unchanged.
Server-Side Setting of <title>
Dynamically set titles in server-side technologies like PHP or ASP.NET:
<?php
$pageTitle = "Dynamically Generated Title";
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo htmlspecialchars($pageTitle); ?></title>
</head>
<body>
<title>
and Single-Page Application Frameworks
Modern frontend frameworks often provide specialized ways to manage titles:
React Helmet Example:
import { Helmet } from 'react-helmet';
function Page() {
return (
<div>
<Helmet>
<title>Title Set Using React Helmet</title>
</Helmet>
{/* Page Content */}
</div>
);
}
Vue Meta Example:
export default {
metaInfo: {
title: 'Page Title Set with Vue Meta'
}
}
Testing Methods for the <title>
Tag
Several ways to verify if the title is correct:
- Check the browser tab.
- Review search engine result previews.
- Use developer tools:
console.log(document.title);
- Analyze with SEO tools.
<title>
and Browser Extensions
Some browser extensions modify page titles, commonly seen in:
- Password managers.
- Tab management tools.
- SEO analysis tools.
Developers should account for these cases and avoid relying solely on titles for page logic.
<title>
in Printing
When printing a page, the title typically appears in:
- The print preview title bar.
- PDF file metadata.
- Some browsers display the title in headers or footers.
CSS can specify titles for printing:
@media print {
title {
display: none;
}
/* Or use generated content */
body:first-child::before {
content: "Print-Specific Title";
display: block;
}
}
<title>
and HTTP Headers
Although rare, servers can set titles via HTTP headers:
X-HTML-Title: Title Set via HTTP Header
Then in HTML:
<title><script>document.write(document.querySelector('meta[http-equiv="X-HTML-Title"]')?.content || 'Default Title')</script></title>
Alternatives to the <title>
Tag
While <title>
is the standard approach, some environments may use alternatives:
- PDF Documents: Have their own title metadata.
- Emails: Use the Subject as the title.
- Desktop Applications: Use window title properties.
<title>
and Web Components
When using <title>
in web components, note:
<template id="my-component">
<title>This title won't work because the title in the template doesn't belong to the document head</title>
<!-- Component Content -->
</template>
The correct approach is to set the document title when the component mounts:
class MyComponent extends HTMLElement {
connectedCallback() {
document.title = "Component Title";
}
}
<title>
and iframes
Titles in iframes do not affect the parent document's title:
<iframe srcdoc="<html><head><title>iframe Title</title></head></html>"></iframe>
The parent document must explicitly get the iframe title:
document.querySelector('iframe').contentDocument.title;
<title>
and SVG
SVG documents can also contain their own <title>
elements for accessibility:
<svg>
<title>A Red Circle</title>
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
This is a different concept from HTML's <title>
tag, despite sharing the same name.
<title>
and Performance Optimization
Frequent title changes may impact performance:
// Bad Practice - Changing the title 60 times per second
function animateTitle() {
let angle = 0;
setInterval(() => {
angle += 0.1;
document.title = `Title Animation ${Math.sin(angle).toFixed(2)}`;
}, 1000/60);
}
Avoid such high-frequency updates, especially on mobile devices.
<title>
and Browser History
Modifying document.title
does not create new history entries:
history.pushState({}, "New Title", "/new-url");
document.title = "New Title"; // Does not create additional history entries
<title>
and Page Load Indicators
Some browsers display loading indicators when the title changes:
document.title = "Loading...";
fetch('/data').then(() => {
document.title = "Loading Complete";
});
<title>
and WebSocket
Real-time applications can update titles via WebSocket:
const socket = new WebSocket('wss://example.com');
socket.onmessage = (event) => {
if(event.data.type === 'notification') {
document.title = `(${event.data.count}) My App`;
}
};
<title>
and Web Workers
Web Workers cannot directly modify titles; use postMessage
:
// Main Thread
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
if(e.data.type === 'setTitle') {
document.title = e.data.title;
}
};
// worker.js
self.postMessage({type: 'setTitle', title: 'Title from Worker'});
<title>
and Content Security Policy (CSP)
CSP typically does not restrict <title>
content but may limit scripts that dynamically set titles:
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
<!-- This script will be blocked -->
<script>document.title = "Dynamic Title";</script>
<title>
and Shadow DOM
<title>
elements inside Shadow DOM do not affect the main document:
const shadow = element.attachShadow({mode: 'open'});
shadow.innerHTML = '<title>Shadow Title</title>';
// Main document title remains unaffected
<title>
and WebAssembly
Modifying titles from WebAssembly requires calling JavaScript:
// Rust Example (wasm-bindgen)
#[wasm_bindgen]
pub fn set_title(title: &str) {
web_sys::window().unwrap().document().unwrap().set_title(title);
}
<title>
and Server Push
HTTP/2 server push cannot directly modify client titles but can send HTML with new titles:
:status: 200
content-type: text/html
<head><title>Title from Server Push</title></head>
<title>
and Web Components API
Document.title
is part of the Document
interface and can be accessed in various ways:
const title = window.document.title;
const title = self.document.title;
const title = document.title;
const title = new Document().title; // New document instance
<title>
and Browser Extension APIs
Browser extensions can modify titles via APIs:
// Chrome Extension Example
chrome.tabs.executeScript(tabId, {
code: 'document.title = "Modified Title";'
});
<title>
and Automated Testing
Verify titles in tests:
// Jest + Puppeteer Example
test('Page title is correct', async () => {
await page.goto('http://example.com');
expect(await page.title()).toBe('Expected Title');
});
<title>
and Page Redirects
During page redirects, browsers immediately display the new page's title:
window.location.href = '/new-page'; // Title immediately changes to the new page's title
<title>
and Browser Cache
Cached pages retain their original titles even if the server's title has changed.
<title>
and Service Worker
Service Workers can intercept requests and modify titles in responses:
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).then((response) => {
if(response.headers.get('content-type').includes('text/html')) {
return response.text().then((text) => {
const modified = text.replace('<title>Original Title</title>', '<title>New Title</title>');
return new Response(modified, response);
});
}
return response;
})
);
});
<title>
and Web Performance
Measure title setting time:
performance.mark('title-start');
document.title = 'New Title';
performance.mark('title-end');
performance.measure('title-update', 'title-start', 'title-end');
console.log(performance.getEntriesByName('title-update')[0].duration);
<title>
and Web Animation API
Although uncommon, title changes can be animated:
let start = 0;
function animateTitle(timestamp) {
if(!start) start = timestamp;
const progress = timestamp - start;
document.title = `Loading... ${Math.min(100, (progress / 1000 * 100).toFixed(0)}%`;
if(progress < 1000) {
requestAnimationFrame(animateTitle);
} else {
document.title = "Loading Complete";
}
}
requestAnimationFrame(animateTitle);
<title>
and WebRTC
Update titles dynamically in video call apps:
const pc = new RTCPeerConnection();
pc.onconnectionstatechange = () => {
document.title = `In Call (${pc.connectionState})`;
};
<title>
and Web Audio API
Audio apps can display playback status:
const audioContext = new AudioContext();
function updateTitle() {
document.title = audioContext.state === 'running'
? "Audio Playing"
: "Audio Paused";
}
audioContext.onstatechange = updateTitle;
<title>
and WebGL
3D apps can display performance metrics in titles:
function render() {
// WebGL rendering logic
const fps = calculateFPS();
document.title = `3D Scene (${fps} FPS)`;
requestAnimationFrame(render);
}
render();
<title>
and WebXR
VR/AR apps can display XR session status:
navigator.xr.requestSession('immersive-vr').then((session) => {
document.title = "VR Session in Progress";
session.onend = () => {
document.title = "VR Session Ended";
};
});
<title>
and Progressive Web Apps (PWAs)
PWAs can distinguish between online/offline states:
window.addEventListener('online', () => {
document.title = document.title.replace("(Offline)", "(Online)");
});
window.addEventListener('offline', () => {
document.title += " (Offline)";
});
<title>
and Web Share API
When sharing pages, the title is often used as the default share text:
navigator.share({
title: document.title,
url: location.href
});
<title>
and Payment Request API
Update titles during payment processes:
const paymentRequest = new PaymentRequest(methodData, details);
paymentRequest.show().then(() => {
document.title = "Processing Payment...";
});
<title>
and Credential Management API
Reflect login status in titles:
navigator.credentials.get({password: true}).then((cred) => {
document.title = `Welcome Back, ${cred.id}`;
});
<title>
and Page Visibility API
Modify titles when the page is hidden:
document.addEventListener('visibilitychange', () => {
if(document.hidden) {
document.title = "Please Come Back!";
} else {
document.title = "Welcome Back";
}
});
<title>
and Fullscreen API
Titles remain visible in fullscreen mode:
document.documentElement.requestFullscreen();
document.title = "Fullscreen Mode"; // Still effective
<title>
and Resize Observer
Update titles in response to layout changes:
const ro = new ResizeObserver(() => {
document.title = `${window.innerWidth}×${window.innerHeight}`;
});
ro.observe(document.body);
<title>
and Intersection Observer
Reflect scroll position in titles:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
document.title = `Viewing: ${entry.target.id}`;
}
});
}, {threshold: 0.5});
document.querySelectorAll('section').forEach(section => {
observer.observe(section);
});
<title>
and Performance Timeline API
Measure the performance impact of title updates:
const observer = new PerformanceObserver((list) => {
for(const entry of list.getEntriesByName('title-update')) {
console.log('Title Update Duration:', entry.duration);
}
});
observer.observe({entryTypes: ['measure']});
<title>
and User Timing API
Mark title update timings:
performance.mark('before-title-update');
document.title = "New Title";
performance.mark('after-title-update');
<title>
and Navigation Timing API
Get the time of title setting relative to navigation start:
const navEntry = performance.getEntriesByType('navigation')[0];
console.log('Title set', performance.now() - navEntry.startTime, 'ms after navigation');
<title>
and Resource Timing API
Although not directly related, compare resource loading and title setting:
const resources = performance.getEntriesByType('resource
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:-文档头部容器
下一篇:<body>-文档主体内容