Scott Colby
Scott Colby

Reputation: 1430

Basic jQuery .load Problem

I am trying to use jQuery's .load function to dynamically load content into my webpage. This seem so simple, but I cannot make it work. To try and figure it out, I made a test page with just basic structure, but the external content still won't load:

jquery.html

<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>

<script>
    $('#foo').load('test.html');
</script>

<div id="foo"></div>

</body>
</html>

test.html

<p>Text text</p>

I'm sure I have made a tiny error, but I can't find it anywhere!

Upvotes: 0

Views: 393

Answers (4)

pdpi
pdpi

Reputation: 4233

Informally, what's happening is that, as your browser reads the code you wrote, it's drawing its contents as it goes along. When it reaches your <script> tag, it executes it. But when $("#foo") gets executed, the browser's still processing the <script> and hasn't reached the part of the code where you told it there's a div called foo, so the browser doesn't know it exists, and jquery will just find nothing.

Of course, the idea that the browser will just sequentially read your code and render it as it goes is naive at best, so while it might seem that just moving the <script> tag to the bottom of the code would work, you're not actually guaranteed it will work. Instead, the browser will notify you when it's done drawing the page by firing a load (and possibly a DOMContentLoaded) event. So all code that depends on the whole html being drawn should be executed in an event handler bound to those events.

jQuery makes waiting for the page to be loaded easy, just use something like this:

$.ready(function() {
  doStuff();
});

Upvotes: 0

Arvin
Arvin

Reputation: 1506

or if you want a shorter code:

$(function() {
    $('#foo').load('test.html');
});

Upvotes: 0

claviska
claviska

Reputation: 12490

You need to wait for the document to be ready before you can access the DOM. Just add a $(document).ready() around your original code:

<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>

<script>
    $(document).ready( function() {
        $('#foo').load('test.html');
    });
</script>

<div id="foo"></div>

</body>
</html>

Upvotes: 0

mVChr
mVChr

Reputation: 50205

You need to encapsulate your script in the $(document).ready() otherwise #foo won't exist when the script is executed:

<script>
    $(document).ready(function(){
      $('#foo').load('test.html');
    });
</script>

Upvotes: 2

Related Questions