jquery blockui several tasks

143 Views Asked by At


I guess this may be pretty obvious, but I'm quite noob regarding front-end.
Scenario is as follows: whenever the user click a button, I need to
1-block the page by means of blockUI
2-clear some stuff
3-load some stuff
4-unblock the page
Let there be a snippet, similar to my current approach:

function reload_data()
{
 //block
 $.blockUI({ message: $('#spinner_div') , css: { top: '50%' , left:'50%' , border:'none'} }); 
 
 //clear stuff
 $('#my_kpi'  ).text(''); //this empty an anchor
 $('#my_report iframe').attr('src',''); //this empty an iframe
 
 //load stuff
 $('#my_kpi'  ).text('loaded');   //this sets an anchor
 $('#inf_prioridad_estado iframe').attr('src','foo.php'); //this loads an iframe
 
 
 //unblock
 setTimeout(function(){ alert("I would like not to unblock until iframes are loaded");},2000);
 setTimeout($.unblockUI, 2000); //will be blocked unless for 2 seconds
 console.log('unblocked');
 
}

I know (think so...)what is happening, but I don't know how to solve it:
$().attr('src','foo.php'); is indeed executed, but goes on to the next statement before the iframe is actually loaded.
Any ideas?
Thank u so much!

1

There are 1 best solutions below

3
James Hill On BEST ANSWER

Once you set the src attribute of the iframe, you need to listen for the load event:

// Set number of frames to be loaded
// This could be done with a jquery selector getting iframe count
var framesToLoad = 2;

function tryUnblockUI() {
  // Frame loaded, decrement framesToLoad count
  framesToLoad--;

  // Once all frames are loaded, unblock UI
  if (frameLoadingCount === 0) {
    //unblock ui here
  }
}

// Load frame 1
$('#inf_prioridad_estado iframe')
  .attr('src', 'foo.php')
  .on('load', tryUnblockUI);

// Load frame 2
$('#inf_prioridad_estado_2 iframe')
  .attr('src', 'foo.php')
  .on('load', tryUnblockUI);