[英]Can I get the include path of the js file - within the js file?
js function 是否有可能找出其代碼的文件路徑? 在運行時。
前任。 <html><head><script src="/js/version-3.2.1/myfile.js" /><head>...</html>
/js/version-3.2.1/myfile.js
const scriptPath = '/js/version-3.2.1/myfile.js' // how do I get this dynamically?:
const version = scriptPath.split('-')[1].split('/')[0];
console.log("the version is " + version)
您可以使用document.currentScript
:
Document.currentScript
屬性返回當前正在處理其腳本且不是 JavaScript 模塊的<script>
元素。 (對於模塊,請改用import.meta
。)需要注意的是,如果腳本中的代碼作為回調或事件處理程序被調用,這將不會引用
<script>
元素; 它只會在最初處理時引用元素。
const scriptPath = document.currentScript.src
// or
const scriptPath = document.currentScript.getAttribute('src')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.