@ wrote... (6 years, 6 months ago)

I know next to nothing about Javascript so I'll need somebody who knows about this stuff to weigh in, but this is how I got jquery to load asynchronously and then fire callbacks.

After watching Breaking the 1000ms Time to Glass Mobile Barrier I tried to get my javascript loading asynchronously. That part is easy, in fact there are easier ways than the method described in the video so I'm not sure why they weren't mentioned. I'm thinking Ilya Grigorik knows his stuff, he's probably forgotten more web stuff than I'll ever know.

// here's the easy way, not sure why it wasn't mentioned
// put async and defer for maximum cross browser likelihood of working
<script type="text/javascript" src="jquery.js" async defer></script>

Anyhow, here's the code.

<head>
  <script language="javascript" type="text/javascript">
    var async_js_events = {}; // the dictionary holding the callbacks

    // callback should accept req object. ie: function(req) {...}
    function async_js_load( name, url, callback ) {
      if ( !( name in async_js_events ) ) async_js_events[name] = [];
      async_js_events[name].push( callback );

      var req = new XMLHttpRequest();

      req.onreadystatechange = function() {
        if( req.status === 200 && req.readyState === 4 ) {
          for( var i=0; i < async_js_events[name].length; i++ ) {
            var cb = async_js_events[name][i];
            cb( req );
          }
        } 
      };

      req.open( "get", url, true );
      req.send('');
    };

    // async load of jquery, then as it's callback add it to the header
    async_js_load( 'jquery', "jquery.js", function( req ) {
      var po = document.createElement( 'script' );
      po.type = 'text/javascript';
      po.innerHTML = req.responseText;

      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore( po, s );
    });
  </script>
</head>

And then somewhere else on the page

...


<script type="text/javascript">
  // when jquery has finished loading use it
  async_js_events['jquery'].push( function(req) {
    $("#reg_list").hover(
      function() { $(this).children('li:not(:first)').fadeIn(200); },
      function() { $(this).children('li:not(:first)').fadeOut(200); }
      );
  });
</script>
Category: tech, Tags: html, javascript
Comments: 0
Click here to add a comment