简体   繁体   中英

How can I preload assets I know I will be requesting via XMLHttpRequest?

I have a page which needs to load and process two large-ish files via ajax. I know in advance that I am going to need to download them, but I can't start the ajax request until another large javascript file has loaded and is ready to process them.

The result is that I end up fetching the large javascript and the large assets in serial rather than parallel, which I think could be nearly twice as fast.

Is it possible to get the browser to preload these assets?

You can see in the below screenshot that production.min.js has to be loaded before base-2.91.wsz and llama-2.91.mp3 even start downloading.

在此处输入图片说明

Sounds like jQuery.when() would do the trick. Straight from the documentation:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {    
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.    
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]    
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"    
  if ( /Whip It/.test( data ) ) {    
    alert( "We got what we came for!" );    
  }    
});

So you would execute all three calls in parallel and continue when all three are finished.

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