How to load page synchronously using jQuery

12,119

Solution 1

In your case, this sounds like it would really be a better idea to implement server-side if possible. In PHP it would be a simple matter of detecting if the cookie you want is set in the $_COOKIE array and outputting the correct page.

Solution 2

AFAIK, JQuery load cannot be synchronous.

You can cet around this witha callback function.

$(document.body).load('hasCookie.html', function(){
//call styling script here
});

Solution 3

You can form it as an AJAX request and populate your page with the response. Set the async option to false. This SO answer has more: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Solution 4

Just change document.location.href to the url of the page.

What you're doing is loading content with ajax and placing it within the page body. You'd do this if you didn't want any resources declared in head to get requested. But there's no point in that since you can do it with caching.

Share:
12,119
Karan
Author by

Karan

Twitter: @karangb Engineer at Facebook 1st class MEng in Computer Science at Imperial College London.

Updated on June 14, 2022

Comments

  • Karan
    Karan almost 2 years

    Currently I am using jQuery to choose what my index page should load depending whether a cookie is set.

    For example, the body tag of the index.html should load hasCookie.html if the cookie is set and noCookieSet.html if no cookie is set.

    My index page currently has:

    load user scripts
    load styling scripts
    
    <html><body></body></html>
    

    The user script has the code that checks whether the cookie is set. If it is, I use jQuery's load to load the content into the body:

    $(document.body).load('hasCookie.html')
    

    However, since this is executed asynchronously, the styling scripts have loaded before the body tag has been updated, hence the body is not styled.

    Is there a way of having a synchronous load, or should am I approaching this in the wrong way?

    EDIT: if it helps, the styling scripts are basically jQueryUI