Skip to content Skip to sidebar Skip to footer

How To Execute Jquery Script Before Page Load?

I need to execute javascript before Page load in ASP.NET application. My function returns user location, and I would like to pass value to server side and load data based on locati

Solution 1:

I need to execute javascript before Page load in ASP.NET application

This requirements makes no sense. Remember how ASP.NET works:

  1. A user request hits the web server
  2. The web server dispatches the request to ASP.NET engine.
  3. The ASP.NET engine instantiates the page and goes through the entire page lifecycle.
  4. The page is rendered as HTML and is sent to the client
  5. The client browser builds the DOM, runs client side javascript, ...

You see that it is impossible to have step 5 execute before step 3 (in which the Page_Load event executes).


Solution 2:

I need to execute javascript before Page load in ASP.NET application.

In that case, you will need to make two page requests. You can't do it with a single page request, since Page_Load() runs before the HTML+JS is even sent to the client.

Instead, have a mini-page that makes the JS call and then either does a postback to the current page, or (probably better), loads a new page. You can pass the location data either through a regular (non-server) form, or perhaps by setting a cookie from JS on the client, or encode it into the query string.

The second page/request will then have the data you need when it's Page_Load() event fires.


Solution 3:

Do an ajax callback using javascript to request the data.


Post a Comment for "How To Execute Jquery Script Before Page Load?"