javascript - How can I "include" js-code from several js-files into main html-file? - Stack Overflow

admin2025-05-02  0

I had a lot of javascript(js)-code in my previous html-file.
I have moved part of the code in another js-files - file1, file2 - see code below.
Before moving I didn't take care about order of functions declarations. It was OK.
After moving the order began to matter.

I have used defer attribute to force the browser to download all the scripts before they start executing. But when the main code starts to execute the browser reported an error - function in file1/2 are not defined.

The question is: how can I move a part of js-code into another js-file and not worry about the order of inclusion of additional files and the order of functions declarations in the main code?

html...
 
<script>
     the main js-code - previously all js-code, including file1 and file2, was placed here
</script>
 
<script defer src="file1.js"></script>
<script defer src="file2.js"></script>

I had a lot of javascript(js)-code in my previous html-file.
I have moved part of the code in another js-files - file1, file2 - see code below.
Before moving I didn't take care about order of functions declarations. It was OK.
After moving the order began to matter.

I have used defer attribute to force the browser to download all the scripts before they start executing. But when the main code starts to execute the browser reported an error - function in file1/2 are not defined.

The question is: how can I move a part of js-code into another js-file and not worry about the order of inclusion of additional files and the order of functions declarations in the main code?

html...
 
<script>
     the main js-code - previously all js-code, including file1 and file2, was placed here
</script>
 
<script defer src="file1.js"></script>
<script defer src="file2.js"></script>
Share Improve this question asked Jan 2 at 12:55 LUNLUN 1031 silver badge7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

So now the order of the functions matters when you moved the old functions from inside script tag to separate files. So in order to achieve the same results as previously, there is so many approaches and strategies to use, one of them is the following:

Use modules approach and manually call your functions, like so:

<script type="module">
    import { functionFromFile1 } from './file1.js';
    import { functionFromFile2 } from './file2.js';

    // Call the functions here without worrying about order
    functionFromFile1();
    functionFromFile2();
</script>

Now like in file(1/2).js you export the functions as following:

export function functionFromFile1or2() {
// Your function code goes here.
}

You will notice that there is no need now for defer.

转载请注明原文地址:http://anycun.com/QandA/1746118885a91929.html