Lkan
Lkan

Reputation: 21

C# Calling JS before page loads

Is it possible to call JS code before a page loads (or before other javascript code is called on the page)? For example: Using webbrowser control, I navigate to "http://google.com", but before any js code on google is executed, I'd like to do something like "alert('one moment!');".

Any ideas as to how I can accomplish this? I'd guess that I have to somehow modify the html before it fully loads, add the js function, then execute it using invokescript, but not sure how I'd go about that.

Upvotes: 0

Views: 2561

Answers (4)

Mohammed Irfan
Mohammed Irfan

Reputation: 1

If you use the C# (Razor Render engine), you can use the following code on top of your top of the page

@if(true){
<script>
 // your script
</script>
}

Upvotes: 0

Ankit
Ankit

Reputation: 6654

Put the following code at the top of your page. This would be called before even whole document loads

<script type="text/javascript">
    // add javascript code
    alert('Page not even loaded but the javascript runs');
</script>

This will do the needful. If you want the script to run post the DOM object is complete and page load is complete, do it in document.ready

Upvotes: 0

Brian P
Brian P

Reputation: 1587

Are you trying to implement a loading screen? I have done that by Forcing a postback on page load, doing the heavy lifting in the postback, then hiding the loading screen when the postback is complete.

Upvotes: 0

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

My first suggestion is to use scripts inside the <head> tag:

<body>
    <head>
    <script type="text/javascript">
        // ...
    </script>

You could use jQuery:

$(document).ready(function()
{
    // ...
});

Or:

window.onload = function()
{ 
    // ...
}

In any case you have to make a special effort not to do this kind of things. It's a very bad practice, especially if it involves user interaction.

Upvotes: 1

Related Questions