Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript in the html body execute when encountered?

I have inherited an ASP.net codebase and I have very limited ASP.net skills. I am struggling to understand why something works and also why it only works in IE.

The following code appears in a page :-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="map.aspx.cs" Inherits="Romtrac.auth_map" Culture="auto" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>
        <% = Resources.Resource.map %>
    </title>
</head>
<body>    
    <form id="adminlw_map_form" action="<%=geturl()%>" method="post"  >

    <% = Resources.Resource.loading %>...
    <textarea name="xml" id="xml" runat="server" style="display:none" cols="1" rows="1"></textarea>
    </form>
    <script language="javascript" type="text/javascript" >
      //submit main form immediately
        document.getElementById('adminlw_map_form').submit();
    </script>
</body>
</html>

This code runs fine in ASP.net. The form is automatically submitted and the page returned is rendered correctly within an Iframe. My question is;

1) Does the javascript within the body just get executed when it is encountered? Is this good practice or should it be executed in response to an event?

2) Why does this not work in other browsers?

like image 566
Steve Weet Avatar asked Feb 28 '26 10:02

Steve Weet


2 Answers

  1. Yes
  2. The javascript is being executed before the browser has fully rendered the page. In this case, the form has not been rendered and is not accessible via the DOM.

The execution needs to happen after the DOM is fully loaded by the browser and can be implemented by encapsulating the call within a function and calling that function via the onload event of the body or by using a javascript library like jquery to hook into the load event of the page.

like image 163
catalpa Avatar answered Mar 02 '26 23:03

catalpa


1) Yes, No. jQuery does it best with it's $(document).ready() function, but you should wait for the page to finish loading before running Javascript.

2) Do #1 and you won't need to worry about this. However I'll leave the floor open to someone with a better answer.

like image 34
Mike Robinson Avatar answered Mar 02 '26 22:03

Mike Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!