简体   繁体   中英

Order of self-invoking function in page load events - javascript/html

I'm looking to find out the order at which a self-invoking js function takes place in terms of the order of events in a page load. I've been googling all over for an answer to this but haven't found anything definitive.

And as for what this actually applies to, I'm adjusting the height of an outer element based on the height of one of it's inner elements (which will vary depending on length of text and screen width)

    var text_elem = document.getElementById('text_elem');
    var textElemHeight = text_elem.offsetHeight;
    var newBkgdHeight = 96 + textElemHeight;
    document.getElementById('background').style.height = newBkgdHeight + "px";

as of now this block is being executed in a self-invoked function as opposed to an onload event since with an onload event there's a weird effect where the height adjusts a second or 2 after the page has loaded, but just wanted to be sure that using a self-invoked function is safe and that there's no chance of the code within it being executed before the HTML DOM loads.

EDIT:

Just as a note, this is working properly using a self-invoking function or IIFE, I just want to make sure it's safe and will consistently work, and be able to explain this better to a colleague if it is.

Here is the relevant code for this situation:

<style type="text/css">
    #background {
        height: 150px;
    }
</style>
......
......
<div id="background">
   <div id="text_elem">
      ${text loaded from somewhere else}
   </div>
</div>
......
......
<script>
(function() {
    var text_elem = document.getElementById('text_elem');
    var textElemHeight = text_elem.offsetHeight;
    var newBkgdHeight = 96 + textElemHeight;
    document.getElementById('background').style.height = newBkgdHeight + "px";
})();
</script>

Your IIFE will execute as soon as the <script> block containing it is loaded.

Since it's located at the end of the HTML, it will be executed after all the earlier HTML is loaded into the DOM.

The execution time is no different than if you hadn't put it in an IIFE at all, but just wrote it as top-level JavaScript code. The only difference from putting it in an IIFE is that the variables are local rather than global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM