[英]How to import javascript function from file without running entire js file?
I have page1.html which uses blah.js.我有使用 blah.js 的 page1.html。 One of the things blah.js does is run a function1() when the page is loaded. blah.js 做的一件事是在加载页面时运行 function1()。 I would like to use function2() from blah.js in page2.html without blah.js running function1().我想在 page2.html 中使用来自 blah.js 的 function2() 而没有 blah.js 运行 function1()。 I thought I could add我想我可以添加
export {function2}
to blah.js and then just import function2() by adding到 blah.js,然后通过添加导入 function2()
<script type = "module">
import { function2 } from './blah.js'
</script>
to page2.html.到 page2.html。 But this seems to have the same functionality as if I just imported the file as normal:但这似乎具有与我正常导入文件相同的功能:
<script defer src="blah.js"></script>
ie function1() runs in page2 in both cases.即 function1() 在这两种情况下都在 page2 中运行。 How can I get access to function2() without running the other parts of blah.js?如何在不运行 blah.js 的其他部分的情况下访问 function2()?
If you import from a module, all of that module's top-level code will run.如果您从一个模块导入,该模块的所有顶级代码都将运行。 That is, given也就是说,给定
console.log('running');
export const foo = 5;
There is no way to import foo
without also logging the text.如果不记录文本,则无法导入foo
。
One good approach to this problem (and a very good practice in general) is to avoid side-effects at the top level of modules.解决这个问题的一个好方法(通常也是一个非常好的做法)是避免模块顶层的副作用。 If you have something that's a side-effect, put it into a function instead, and export that function, so that it only runs on demand, instead of every time anything from the file is imported.如果您有一些副作用,请将其放入 function,然后导出该 function,以便它仅按需运行,而不是每次导入文件中的任何内容时运行。
So, you probably want to change your file to something like:因此,您可能希望将文件更改为:
export const runFunction1WhenPageLoads = () => {
const fnToRun = () => {
// insert code here
};
if (document.readyState === 'complete') {
fnToRun();
} else {
window.addEventListener('DOMContentLoaded', fnToRun);
}
};
export const function2 = () => {
// insert code here
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.