Quiero que se ejecuten múltiples llamadas ajax síncronas en la carga de la página en segundo plano (en una función asíncrona sin esperar) y dejar que la página se cargue para el usuario sin esperar. He agregado mi solución hacky, pero quiero saber cómo JavaScript ya proporciona una solución real/formal para el problema dado
let dt_pl = new Date(); function time_taken_to_reach_here(){ let diff_ms = new Date() - dt_pl; return diff_ms; } $(function(){ console.log('page loaded ', time_taken_to_reach_here()); // Time in milliseconds // 132 when non_async // 139 when not_really_async // 160 when hacky_async_back_ground });El tiempo anterior también se comparte como imágenes al final de la pregunta. El siguiente es el código para diferentes métodos para ejecutar un montón de llamadas ajax. La pregunta no se trata de tener un enfoque alternativo para resolver un problema específico , sino que en realidad solo envuelve el código JavaScript de ejecución prolongada en realmente asíncrono
function ajax1(){ $.ajax({ url: '/read_thing_information_schema', success: function(data){ /* use data */}}); } function ajax2(){ $.ajax({ url: '/read_other_information_schema', success: function(data){ /* use data */}}); } function non_async(){ console.log('Function used => non_async'); console.log('starting ajax calls ', time_taken_to_reach_here()); ajax1(); ajax2(); after_tables_loaded(); console.log('all called and call backs done ', time_taken_to_reach_here()); } function not_really_async(){ console.log('Function used => not_really_async'); (async function(){ non_async(); })(); } function hacky_async_back_ground(){ console.log('Function used => hacky_async_back_ground'); console.log('starting ajax calls ',time_taken_to_reach_here()); $.ajax({ url: '/dummy_path_that_actually_does_not_exist', complete: function(){ ajax1(); ajax2(); after_tables_loaded(); console.log('all call backs done ',time_taken_to_reach_here()); } }); console.log('all called ',time_taken_to_reach_here()); }Llamar a uno de los métodos anteriores
// hacky_async_back_ground(); // non_async(); not_really_async();Resultados
llamada función non_async
llamado not_really_async
llamado con hacky_async_background