Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 287
  • Last Modified:

javascript blocks being ignored?

If I put 2 javascript blocks inside an html page, the 1st js block gets ignored and the 2nd one gets executed. Like so:

<script language="javascript" type="text/javascript">
   alert("alert #1")
</script>

<script language="javascript" type="text/javascript">
   alert("alert #2")
</script>

Open in new window



When I load the page, I only see "alert #2". Can someone confirm this behavior is real? The reason I have 2 js blocks and not just 1 is because the 1st one is part of my asp.net master page, and the 2nd is reserved for individual pages. The master page gets merged at runtime with individual pages (like an include/header idea), so both js blocks end up on the page together.

Note: The jquery library is referenced and is being invoked further down the page. Could this be impacting things?

I am using IE8.

Any ideas?
0
SweatCoder
Asked:
SweatCoder
  • 2
1 Solution
 
BadotzCommented:
You are depending on the page to execute your JavaScript when it wants to.

You shoul instead wrap your code like this:


<script type="text/javascript">

function page_load() {
    
    alert("alert #1");
    alert("alert #2");
}

window.onload = page_load;

</script>

Open in new window

0
 
BadotzCommented:
Or, since you use jQuery, use the "ready" syntax (visit the jQuery home page for details).
0
 
ProculopsisCommented:

It looks like .net is getting in the way, for reliable execution of JavaScript, use one of the following methods in your code behind:

  .RegisterClientScriptBlock()
  .RegisterStartupScript()
0
 
SweatCoderAuthor Commented:
This solved my problem! Just a side note though, those methods are depracated. Here is the reference for the replacement:

http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now