阿里云主机折上折
  • 微信号
Current Site:Index > The `<base>` tag specifies the base URL.

The `<base>` tag specifies the base URL.

Author:Chuan Chen 阅读数:41566人阅读 分类: HTML

The <base> tag is used to specify a base URL for all relative URLs on a page. It must be placed in the <head> section, and a document can have at most one <base> tag. By setting the base URL, it simplifies the path notation for resources like links and images on the page.

Basic Syntax of the <base> Tag

The syntax of the <base> tag is very simple, with only two optional attributes:

<base href="base URL" target="target window">
  • href: Specifies the base URL for all relative URLs on the page.
  • target: Specifies the default opening method for all hyperlinks and forms (e.g., _blank, _self, etc.).

The href Attribute of the <base> Tag

The href attribute is the core functionality of the <base> tag. It defines the resolution base for all relative URLs in the document. Once <base> is set, the browser combines relative URLs in the page with the base URL to form complete URLs.

<head>
  <base href="https://example.com/images/">
</head>
<body>
  <!-- Will actually load https://example.com/images/pic.jpg -->
  <img src="pic.jpg">
  
  <!-- Will actually navigate to https://example.com/images/docs/intro.html -->
  <a href="docs/intro.html">Introduction</a>
</body>

The target Attribute of the <base> Tag

The target attribute sets the default opening method for all links and forms on the page, which is useful when you need uniform control over link behavior.

<head>
  <base target="_blank">
</head>
<body>
  <!-- All links will open in a new window -->
  <a href="page1.html">Page 1</a>
  <a href="page2.html">Page 2</a>
  
  <!-- Can individually override the base target setting -->
  <a href="page3.html" target="_self">Page 3</a>
</body>

Priority Rules of the <base> Tag

When there are conflicts in URL resolution, the browser follows these priority rules:

  1. Explicitly specified full URLs (starting with http://, https://, etc.) are unaffected by <base>.
  2. When <base> is set, relative URLs are resolved based on the base URL.
  3. When <base> is not set, relative URLs are resolved based on the current document URL.
<head>
  <base href="https://cdn.example.com/assets/">
</head>
<body>
  <!-- Uses the base URL -->
  <img src="logo.png"> <!-- Loads https://cdn.example.com/assets/logo.png -->
  
  <!-- Full URLs are unaffected -->
  <img src="https://example.com/logo.png">
  
  <!-- Document-relative paths (starting with /) are based on the base URL's domain -->
  <a href="/about">About</a> <!-- Navigates to https://cdn.example.com/about -->
</body>

Practical Use Cases for the <base> Tag

CDN Acceleration for Static Resources

By setting the base URL to a CDN domain, you can easily achieve static resource acceleration:

<head>
  <base href="https://cdn.example.com/2023/assets/">
</head>
<body>
  <!-- All resources are automatically loaded from the CDN -->
  <img src="images/header.jpg">
  <script src="js/app.js"></script>
  <link rel="stylesheet" href="css/style.css">
</body>

Multi-Environment Deployment

When switching between environments (development/test/production), only the base URL needs to be modified:

<head>
  <!-- Development environment -->
  <base href="http://localhost:8080/">
  
  <!-- Production environment -->
  <!-- <base href="https://example.com/"> -->
</head>

Single-Page Application Routing

In single-page applications, <base> can help correctly handle routing:

<head>
  <base href="/app/">
</head>
<body>
  <!-- Routing links are based on the /app/ path -->
  <a href="users">User List</a> <!-- Actual path is /app/users -->
  <a href="settings">Settings</a> <!-- Actual path is /app/settings -->
</body>

Notes on Using the <base> Tag

  1. Position Restriction: <base> must appear in the <head> section and precede any other elements containing URLs.
  2. Quantity Restriction: A document can have only one <base> tag.
  3. Anchor Impact: <base> affects the behavior of in-page anchors.
  4. JavaScript Impact: document.baseURI will reflect the <base> setting.
<head>
  <base href="https://example.com/subdir/">
</head>
<body>
  <div id="content"></div>
  
  <script>
    // Output: https://example.com/subdir/
    console.log(document.baseURI);
    
    // Example using the base URL
    fetch('api/data').then(...); // Request is sent to https://example.com/subdir/api/data
  </script>
</body>

The <base> Tag and CSS Paths

The <base> tag does not affect relative paths in CSS. Relative paths in CSS files are always relative to the CSS file's own location:

<head>
  <base href="https://example.com/images/">
  <link rel="stylesheet" href="css/style.css">
</head>

<!-- Contents of style.css -->
.bg {
  background-image: url('../images/bg.jpg'); /* Path is relative to the CSS file's location */
}

Browser Compatibility of the <base> Tag

The <base> tag is fully supported by all modern browsers, including:

  • Chrome
  • Firefox
  • Safari
  • Edge
  • Opera
  • Internet Explorer 9+

For older browsers that do not support <base> (e.g., IE6-8), relative URLs in the page will fall back to being resolved based on the current document URL.

Alternatives to the <base> Tag

In some cases, the following alternatives can be used:

  1. Using Root-Relative Paths (starting with /):

    <img src="/images/logo.jpg">
    
  2. Dynamic Setting via JavaScript:

    document.querySelectorAll('a[href^=""]').forEach(link => {
      link.href = 'https://example.com' + link.getAttribute('href');
    });
    
  3. Server-Side URL Rewriting:

    location / {
      rewrite ^/(.*)$ https://cdn.example.com/$1;
    }
    

The <base> Tag and SEO

Using the <base> tag has the following SEO implications:

  1. Search engines correctly resolve links based on <base>.
  2. Ensure the base URL matches the canonical URL.
  3. Avoid dead links caused by incorrect base URL settings.
<head>
  <base href="https://example.com/">
  <link rel="canonical" href="https://example.com/current-page">
</head>

Debugging Tips for the <base> Tag

When issues arise with the <base> tag, you can debug using the following methods:

  1. Check the value of document.baseURI:

    console.log(document.baseURI);
    
  2. Use browser developer tools to observe the actual URLs of network requests.

  3. Verify whether the base URL ends with a slash (recommended):

    <!-- Recommended -->
    <base href="https://example.com/dir/">
    
    <!-- Not recommended -->
    <base href="https://example.com/dir">
    

The <base> Tag and Web Components

When using web component technologies like Shadow DOM, the behavior of the <base> tag differs:

  1. Relative URLs inside Shadow DOM are unaffected by the document-level <base>.
  2. Each Shadow DOM can have its own URL resolution context.
<head>
  <base href="https://example.com/">
</head>
<body>
  <div id="host"></div>
  
  <script>
    const shadow = document.getElementById('host').attachShadow({mode: 'open'});
    shadow.innerHTML = `
      <!-- This image's path is relative to the main document and unaffected by Shadow DOM -->
      <img src="image.png"> <!-- Loads https://example.com/image.png -->
    `;
  </script>
</body>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.