Question

I have 2 HTML files, 1.html and 2.html.

  • 1 is the main page, which loads 2 by ajax and stuff its content into a div.
  • In 1, there are 3 script blocks - A, B, and C.
    • The $(document).ready() in block B calls a function in block C.
    • There are no errors.
  • In 2, there are 3 script blocks - P, Q, and R.
    • The $(document).ready() in block Q calls a function in block R.
    • It gives an error.

It seems that when some Javascript is loaded through ajax, it cannot call functions in a script block that appears later (but not earlier) in the same file. Why? Is this expected behaviour?

Source code

1.html

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Script block A -->
<script type='text/javascript'>
    function A() {alert('A');}
</script>

<div>x</div>

<!-- Script block B -->
<script type='text/javascript'>
    $(function() {
        A(); B(); C();

        $("#ajax_load_result").load("2.html");
    });

    function B() {alert('B');}
</script>

<div>x</div>

<!-- Script block C -->
<script type='text/javascript'>
    function C() {alert('C');}
</script>

<div id='ajax_load_result'>y</div>

2.html

<div>x</div>

<!-- Script block P -->
<script type='text/javascript'>
    function P() {alert('P');}
</script>

<div>x</div>

<!-- Script block Q -->
<script type='text/javascript'>
    $(function() {
        P(); Q(); R();
    });

    function Q() {alert('Q');}
</script>

<div>x</div>

<!-- Script block R -->
<script type='text/javascript'>
    function R() {alert('R');}
</script>

<div>x</div>

Output

It alerts A, B, C, P, Q, then gives an error message.

Error messages

Opera 12.11:

Unhandled Error: Undefined variable: R

Chrome 23.0.1271.97 m:

Uncaught ReferenceError: R is not defined

IE 9:

SCRIPT5007: The value of the property 'R' is null or undefined, not a Function object

Was it helpful?

Solution

In 2.html $(document).ready fires immediately because the dom has already been built and at that point the script block containing R hasn't been reached yet and hence R is not defined. In 1.html the whole page loads before $(document).ready therefore C get defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top