Search code examples
javascriptdeferred-executiondeferred-loading

Can anonymous function be used to defer js on load?


I just read about deferring js on load. I found Particks article pretty interesting http://www.feedthebot.com/pagespeed/defer-loading-javascript.html.

I took a look at facebook and googles js code. They are all using anonymous functions so I was wondering whether this is deferring js to load after page is loaded?

 (function(d, s, id){
   var js, fjs = d.getElementsByTagName(s)[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement(s); js.id = id;
   js.src = "http://connect.facebook.net/en_US/sdk.js";
   fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));

or is Patricks recommendation the only way to really defer loading js after page is loaded?

<script type="text/javascript">
  function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild(element);
  }
  if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

thx, i really appreciate your expertise!


Solution

  • Both will download the script asynchronously and defer the execution after it is loaded, but the second script waits with starting to load the script until all other resources (including images!) have been loaded (which seems a bit late to me actually).

    They are all using anonymous functions so I was wondering whether this is deferring js?

    No, those IEFEs are only used to structure the code, they do execute immediately. What does defer the js is the dynamic creation of <script> elements.