Lazy loading and Javascript

The Widget Framework supports lazy loading of widgets, groups and areas. Any page fragments that are lazy-loaded are only loaded if required for the current device, and only after the main page document has been loaded. This means you have to be careful when invoking Javascript functions to operate on lazy-loaded fragments. If you invoke them on the document ready event then they may not work in many cases because the addressed element is not yet present in the DOM.

If a function is invoked for a widget on the document ready event inside the widget itself, then it will work even if the widget is lazy-loaded. For example:

<div class="widget awesome-slideshow" id="slideshow-1">
    <!--content omitted-->
</div>

<script type="text/javascript">
  $(document).ready(function(){
     $(".awesome-slideshow").awesomeSlideshow();
  });
</script>

The above function call will not work, however, if it is made in the page's head and awesome-slideshow is lazy-loaded - because the addressed element will not have been loaded when the page's ready event fires.

The Widget Framework therefore provides a custom event called fragmentReady that fires after all lazy-loaded fragments have finished loading. So calling this function from the page's head as follows:

$(document).on("fragmentReady", function(){
  $(".awesome-slideshow").awesomeSlideshow();
});

will work whether or not awesome-slideshow is lazy-loaded.