Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script's async property && document.ready?

I create a script element (document.createElement('script')....) I set its async property by: x.async=true

Which means that the scripts are not blocking and the execution order between each other - is not preserved ( as opposed to defer (which also waits for dom to load.))

Question :

But if I set the async attribute - does it mean that I must use document.ready ? because I could run a method which is declared in the script file which is future to be downloaded - hence error.

like image 334
Royi Namir Avatar asked Feb 12 '26 20:02

Royi Namir


1 Answers

From personal experience, it is better to use document ready or window load in the async script file just to be safe.

This is because after the first load, the JavaScript file would be cached by the browser, and depending on the browser/circumstances, can load from cache and try to execute before the DOM is ready.

like image 110
Benno Avatar answered Feb 15 '26 09:02

Benno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!