Thursday, June 18, 2009

Stop Web Page submit before it is fully loaded in Browser?

Once came across a situation where page loading is slow due to required image loading in JavaScript. Some of the variables are required to set at end of the page load in order to function it as expected. User was clicking on button to post back the page. But, since page is not loaded fully and required variables are not set, post back was not working as expected. To fix this, required a mechanism which will hold past back until page is fully loaded. Below post describes solution to this problem.

Why this check is required?
Requirement is to stop user from submitting web form before page is fully loaded on browser.
How to achieve this?
Find some way to indentify whether page is fully loaded and check this in form submit function every time before submitting form.
Assumption:
Images are loaded at last in page loading life cycle at browser.
JavaScript Solution
Following function checks for all images on page and find if all loaded? If at least one found to be not loaded it returns.
Where to call this method in Page?
Call this function in method being called onSubmit event.
How to DO this in ASP.NET?
In ASP.NET page, Java Script method “WebForm_OnSubmit()”, which is being called when you submit form. You can override this function by adding same function again with additional check for page loaded. Please note that it is necessary that new function should render after standard ASP.NET method is rendered.
Sample
function imagesLoaded()
{
// return variable
var imagesloaded = true;
// All images are saved in an array called document.images. Very usefull
var images = document.images;
// Loop through all the images
for (var i = 0;i
{
if(images[i].complete == false)
{
imagesloaded = false;
break;
}
}
// This will return 0 if one or more images are not loaded and 1 if all images are loaded.
return imagesloaded;
}
function WebForm_OnSubmit()
{
if(!checkImages() )
return false;
… // Standard ASP.NET Code here
}

Post a Comment