LoginSignup
11

More than 5 years have passed since last update.

HTMLのbaseタグをつけたり消したりしてみたときの挙動

Last updated at Posted at 2015-03-05

baseタグというものがあります。
https://developer.mozilla.org/ja/docs/Web/HTML/Element/base

HTML Base 要素 () は、ドキュメント内に含まれるすべての相対 URL の基点となる URL を指定します。

というもので、例えば

<base href="http://www.google.com" />
<img src="/sample.jpg" />

とあった場合、この画像のsrcは "http://www.google.com/sample.jpg" となります。

複数書く

このタグは先勝で、複数書いた場合は最初の href が有効になります。

使用補足: 複数の 要素が指定された場合、最初の href と最初の target の値が使用され、他はすべて無視されます。

途中で書く

以下のようなJSでごにょごにょっと書きだした場合

  • localhostで立ち上げています
  • 簡単な実験のためdocument.writeを使っています
(function(){
  document.write("<img src='/1.jpg' />");
  document.write("<base href='http://www.google.com' />");
  document.write("<img src='/2.jpg' />");
})();

とすると、http://localhost/1.jpghttp://www.google.com/2.jpg にリクエストが行きます。

途中で消す

(function(){
  document.write("<img src='/1.jpg' />");
  document.write("<base href='http://www.google.com' />");
  document.write("<img src='/2.jpg' />");
  setTimeout(function(){
    document.querySelector("base").remove();
    var img = document.createElement("img");
    img.setAttribute("src", "/3.jpg");
    document.body.appendChild(img);
  }, 1000)
})();

とすると、http://localhost/1.jpghttp://www.google.com/2.jpg とした後に、 http://localhost/3.jpg にリクエストが行きます!

消すとbaseが無くなります!

つまりこれを繰り返すと、同じパスだけど、必要なタイミングで必要な base を適用してリクエストが出来る!

まとめ

普通の生活にはなんの役にもたたないと思います

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11