I have page1.html which uses blah.js. One of the things blah.js does is run a function1() when the page is loaded. I would like to use function2() from blah.js in page2.html without blah.js running function1(). I thought I could add
export {function2}
to blah.js and then just import function2() by adding
<script type = "module">
import { function2 } from './blah.js'
</script>
to 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>
i.e. function1() runs in page2 in both cases. How can I get access to function2() without running the other parts of blah.js?
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.
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.
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
};