0

I have an HTML page that i ship to the browser and it contains a couple of script tag.

This is my index.html file:

 <body> <div id="app"></div> <script src="src/index.js"></script> <script> window.test = true; </script> </body> </html> 

And this is my src/index.js file:

<script> const test = () => { if (window.test) { console.log("wow!"); } }; test(); </script> 

In the HTML file, i define window.test after i run the src/index.js. src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.

What is the order in which these scripts will run? Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?

CodeSandbox: https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

2 Answers 2

1

to guarantee that test function is only call after variable is setted why not use a custom event

<script src="src/index.js"></script> <script> window.test = true; const event = new Event('test-setted'); document.dispatchEvent(event); </script> 

and in index.js

<script> const test = () => { if (window.test) { console.log("wow!"); } }; document.addEventListener('test-setted', function (e) { test(); }, false); </script> 
Sign up to request clarification or add additional context in comments.

6 Comments

Is the running order of multiple scripts not guaranteed?
with this solution the order is not an issue (your are not dependent of the order of different script) while you don't receive the event the function is not run
Yes I understand and thanks for it, I'll definitely try it. I was just wondering in general how the executive order is determined.
I understand the best i can give you is the specification of script order html.spec.whatwg.org/multipage/… the specification say it is executed in the order where it is include
but my advice is if you have to "synchronize" several scripts it's better to use promise, event and other mecahnism that don't need a certain order to succeed
|
1

In JS called from HTML file the order of the scripts are just like their order of writing in this file "always" will be in that order, which means that in your example window.test Will always have a null value in index.js so nothing will be printed in the console

1 Comment

That's not the case though, it is always printed: codesandbox.io/s/javascript-forked-utgh8?file=/index.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.