2

If I load a script asynchronously like this

<script type="text/javascript">
    (function () {
        var js = document.createElement('script');
        js.type = 'text/javascript';
        js.async = true;
        js.src = '<%=BundleTable.ResolveUrl("~/js") %>';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(js, s);
    })();
</script>

what event fires once the async stuff is finished loading and the dom is finished loading?

3
  • jQuery(function($){$.getScript('...url...', function(){...callback...});}); is so much simpler... Commented Sep 29, 2011 at 4:51
  • part of what im loading in that request IS jquery Commented Sep 29, 2011 at 12:39
  • 1
    You would want to do js.onload = function() {} there. See here for more info: stackoverflow.com/a/28002292/1329367 Commented Apr 28, 2015 at 17:21

1 Answer 1

3

Every event has it's own notification mechanism so there is no generic answer. For example, you can read about how to detect when a dynamically loaded script is done loading here and here. These days, you can save yourself a ton of time by using a good framework like YUI or jQuery as they most have built-in cross-browser support for these types of events.

For the DOM finished loading, there is no single cross-browser mechanism that gets you the earliest possible time when it's finished loading. If you look at a jQuery implementation of $(document).ready(), you will see several techniques employed (listening for "DOMContentLoaded" event, the earliest time that a setTimeout() will fire, listening for window load(), document onreadystatechange event, etc...) in order to support this functionality cross browser.

The window.onload event will guarentee safe DOM access, but it also waits for all images to finish loading which is much later than neccessary. These other techniques are used to get earlier safe access.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.