shinsenter / defer.js

🥇 A lightweight JavaScript library that helps you lazy load (almost) anything. Defer.js is dependency-free, highly efficient, and optimized for Web Vitals.
https://shinsenter.github.io/defer.js/
MIT License
277 stars 45 forks source link

Question: is Defer.js synchronous #92

Closed richtrefz closed 3 years ago

richtrefz commented 3 years ago

If I make multiple calls to Defer.js to load different .js files, is it guaranteed that they will load in the same order.

Defer.js ('https://example.com/file1.js')
Defer.js ('https://example.com/file2.js')

If file1.js has a function that file2.js requires, will file1.js always load first? So file2 call will be successful?

shinsenter commented 3 years ago

@richtrefz

Basically yes, they will be loaded in the same order as you write (with Javascript processing technology on current browsers). But this is unlikely to be true for the case if future browser's queue is parallelized for javascript files, then the file that is loaded first will be run first.

You can ensure the order of loading and execution of js files by defering the js files of the libraries first, then in Defer.js’scallback function you may call to js files that call to functions of previously loaded libraries.


Defer.js ('https://example.com/file1.js', 'library1', 200, function(){
  Defer.js ('https://example.com/file2.js');
});
richtrefz commented 3 years ago

Thank you for the quick response. I wondered if the callback was the best way to be sure.

Thanks for this library - good work

shinsenter commented 3 years ago

@richtrefz Thank you. Have a great day!