It depends when you want the code to run. If you want the code to execute ASAP you can use an IIFE but there is really no point using an IIFE if you don't use it to protect your variables and/or not polluting the global scope.
(function initialize() {
// do somthing
}());
or
// do somthing
will execute at the same point in time.
If you want to defer execution there are three points in time usually used by web devs. <script>
s at bottom, DOMContentLoad and window.onload.
<script>
s at bottom will execute after they are fetched from the server.DOMContentLoaded
basicly execute as soon as</html>
has been read by the HTML parser.- very simplified
window.onload
executes after all CSS,<img>
es and<script>
s have been loaded.
Note that in reality, with attributes like async
and defer
on <script>
s, this is more complex, . This is why there is a mountain of resource loaders available.