[英]How can I add the URL's root path to the paths of my JS files?
因此,我有一个Web应用程序,在我的计算机上的localhost:XXXXX
上运行(其中XXXXX
是端口号),但是在生产环境中,它运行在webappurl.com/portal
。 问题是,当我对JS文件使用相对路径时,它认为根URL只是/
而不是/portal
。
有没有办法让我检查根路径,例如使用location.pathname
,然后将其添加到每个JS文件路径的开头?
举个例子
<script type="text/javascript" src="/Scripts/example.js"></script>
并将其更改为此
<script type="text/javascript" src="/portal/Scripts/example.js"></script>
我想避免对根路径进行硬编码,主要是因为这不是最佳实践,而且还因为根路径在我的开发环境中是不同的,并且我不想不断地来回更改路径,或者必须保留单独的文件。
虽然“基本”元素似乎可以解决问题,但问题是我们正在处理一个基本情况,具体情况取决于部署环境。 一种解决方案是在发现环境后引导加载脚本。 我在生产中使用了类似的方法:
<script>
(function (){
var
// All the JS files we want to load
script_list = [ 'foo.js', 'bar.js', 'bang.js' ],
// Our JS directory
script_base = '/js/',
doc_path = document.location.pathname,
base_list = doc_path.split('/'),
append_script_tag, base_path, i;
// pop-off the document name from the location to
// get the directory only
base_list.pop();
base_path = base_list.join('/');
// a handy script tag appender function
append_script_tag = function ( script_url ) {
var script_obj = document.createElement( 'script' );
script_obj.src = script_url;
script_obj.charset = 'utf8';
script_obj.type = 'text/javascript';
document.body.appendChild( script_obj );
};
// now loop through the list of js files and write the script tags
for ( i = 0; i < script_list.length; i++ ) {
append_script_tag( base_path + script_base + script_list[ i ] );
}
}());
</script>
繁荣,您完成了:)
当然,如果可以摆动相对路径,则总是更好。 但是有时候,你做不到。 例如,有时使用本地文件进行测试,但在生产中使用CDN。 您可以根据环境加载不同的库,这种方法是确定使用环境的一种方法。
干杯,祝你好运!
签出base
标签。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
它使您可以为所有相对文件引用指定基本URL。
我认为它将对您非常有帮助;)
带斜杠的路径不是相对的,而是绝对的。 /
只是指向应用程序或站点的根目录。 您可以使用base
标记对此进行修改,有关更多信息,请参见kmiklas答案。
不过,就您而言,省略斜线可能就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.