在我的脚本中,有很多@requires
。看起来像:
@require pathA/file1
@require pathA/file2
有时我需要更改pathA
,之后它看起来像这样:
@require pathB/file1
@require pathB/file2
是否可以使用如下变量:
PATH = pathA
@require $PATH/file1
@require $PATH/file2
最佳答案
用户脚本的元数据 block (包括它的 @require
)在加载脚本后无法更改,但您可以创建一个辅助函数,它接受在脚本 URL 中并将该脚本附加到 DOM:
const appendScript = url => new Promise(
(resolve) => {
const script = document.createElement('script');
script.onload = resolve;
script.src = url;
document.body.appendChild(script);
}
);
const path = 'pathA'; // change this string when needed
Promise.all([
appendScript(path + '/file1'),
appendScript(path + '/file2')
])
.then(() => {
// everything is loaded
});
实时片段示例,以便您可以看到代码的工作情况:
const appendScript = url => new Promise(
(resolve) => {
const script = document.createElement('script');
script.onload = resolve;
script.src = url;
document.body.appendChild(script);
}
);
const path = 'pathA'; // change this string when needed
Promise.all([
appendScript('https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js'),
appendScript('https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js')
])
.then(() => {
console.log('React is loaded!');
});
请注意,这将导致脚本被加载到页面中,而不是沙箱中,尽管这可能与您的情况无关。
关于javascript - 如何在@require (Greasemonkey) 中使用自定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637238/