I have 2 HTML files, 1.html and 2.html.
div
.$(document).ready()
in block B calls a function in block C.$(document).ready()
in block Q calls a function in block R.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?
<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>
<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>
It alerts A
, B
, C
, P
, Q
, then gives an error message.
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
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.