Atara
Atara

Reputation: 3569

Using load() and onLoad()

I have a few pages with the same header and footer. I want to use jQuery load function as -

$("#header").load("template.html  #template_h1");   
$("#footer").load("template.html  #template_f1");

My problem:

I tried to run them in $(document).ready(function() but it is too late. the span tags in the header\footer are not converted.

Which event can I use?

Upvotes: 0

Views: 1822

Answers (3)

Seain Malkin
Seain Malkin

Reputation: 2303

Perhaps you could keep a reference of the onload function, do your stuff, then run the original onload function. If you place this just inside the body tag or include it as a script after the script that generates the intial onload it should work as expected.

var oldOnLoad = window.onload;

window.onload = function() {
   oldOnLoad();
}

EDIT To clarify, you need to call oldOnLoad after the header and footer have downloaded.

var oldOnLoad = window.onload;
var headerComplete = false, footerComplete = false;

var callOldOnLoad = function() {
    if (headerComplete && footerComplete) {
        oldOnLoad();
    }
}

window.onload = function() {
    $("#header").load("template.html  #template_h1", function() {
        headerComplete = true;
        callOldOnLoad();
    });   
   $("#footer").load("template.html  #template_f1", function() {
        footerComplete = true;
        callOldOnLoad();
    });
}

Haven't tested this, but you might run in to a problem of the DOM not updating before you call oldOnLoad. So you may need to put that in a setTimeout.

setTimeout(function() {oldOnLoad();}, 0);

Upvotes: 2

Pekka
Pekka

Reputation: 449425

.load() is asynchronous, so you can never rely on the elements getting loaded in time, no matter how early you make the call. You'd have to make the .load() synchronous (ie. block the page until it the request has finished) but that is a terrible idea.

This is not a good way to do templating IMO. Also, you're likely to slow down your page load significantly by requiring two requests to complete before the page looks right.

If at all possible, include these template parts from server side.

Upvotes: 2

ATOzTOA
ATOzTOA

Reputation: 35950

Just place your code inside the <body> just after you define the header and footer elements in HTML.

Example:

<body>
    <div id="header">Foo</div>

    <script type="text/javascript">
        $("#header").load("template.html  #template_h1");
    </script>

    <!-- Other Content -->

    <div id="footer">Bar</div>

    <script type="text/javascript">
        $("#footer").load("template.html  #template_f1");
    </script>
</body>

Also, you can place the CSS inclusion at end of the file to load the CSS after your code.

Upvotes: -1

Related Questions