获取当前 JS web 组件的路径

Get the path to the current JS web component

我有一个 JS Web 组件需要加载其他资源(特别是 srciframe 它添加到 DOM,但这对具有相对路径的任何资源)。

此资源需要相对于调用页面指定,我可以从 window.location.

中轻松获得

但是,它需要指向 src 的文件是相对于正在执行的 JS 文件的,因为它是一个组件,所以我不确定它会在哪里。

所以:

example.com/index.html 
  |__> {unknown path}/web-component.js
  |__> {unknown path}/resource.html <-- I want to get this

该组件可能位于 node_modulesbower_componentswebpackOutput 或任何地方,但它创建的 DOM 需要指向与它相同的位置服务于,而不是执行它的页面。

由于此代码在 Web 组件中 document.currentScriptnull 并且 document.getElementsByTagName('script') 可能不包含该组件。

我有一个潜在的解决方案,但它存在潜在的浏览器兼容性和性能问题。

想法是new Error().stack包括执行文件的路径。

所以...

// Get stack string
const stack = new Error().stack.split('at');

// Get the last entry
const scriptPath = stack[stack.length - 1].trim();

// The component will share the path up to the last slash
const componentPath = scriptPath.substring(0, scriptPath.lastIndexOf('/'));

它依赖于堆栈的格式,堆栈的内容,并且new Error()在加载时不会引起任何性能问题,因此欢迎提供更好方法的答案!