1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HTMLにおける相対パスの開発環境と本番環境での違いをなんとかする

Posted at

相対パスとは

相対パスは、HTMLにおいてはそのファイルからみた相対的な位置を表現したパスであり、要は同じフォルダにあるファイルなどを参照するのに使われます。
しかし、常にこれが同じになるとは限らず、かつ開発時と本番時を揃えるのが面倒くさい時にはなんとかしないといけません。
HTMLでは相対パスはbaseタグで決められます。JavaScriptではdocument.baseURIで取得できます。
しかしdocument.baseURIは読み取り専用です。

相対パスを変更する。

baseタグを利用すれば相対パスを変更できます。なんでか知らないですがdocument.baseURIでは変更できないので、baseタグにid属性をつけてhref属性を変更することで相対パスを変更できます。
この際にスクリプトなどは再読み込みされるようなので、パスが変更されることによって別のスクリプトが動作することになったりする可能性があります。

document.querySelector("#base").href=location.href;
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?