How to load page synchronously using jQuery

后端 未结 6 1105
遥遥无期
遥遥无期 2021-01-23 04:03

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

相关标签:
6条回答
  • 2021-01-23 04:41

    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.

    0 讨论(0)
  • Try

    $(document).ready(function() { $(document.body).load('hasCookie.html'); });
    

    This will postpone loading until after everything else is already there.

    0 讨论(0)
  • 2021-01-23 04:42

    This is how i do it.

    You can attach Style and Javascript upon callback from the Ajax Function.

      $.ajax({
        url: somePage,
        success:function(ajaxData){
    
                            //ATTACH AND RUN CORRESPONDING PAGE SCRIPT
                            var script = somePage + '.js';
                            $.getScript(script);
    
    
    
                            //ATTACH CORRESPONDING STYLE SHEET
                            var style = document.createElement('link');
                            style.type = 'text/css';
                            style.href = '/css/'+somePage+'.css';
                            style.rel = 'stylesheet';
                            style.media = 'screen';
    
                            document.getElementsByTagName('head')[0].appendChild(style);
    
                           //ADD HTML RETURNED
                           $('body').html(ajaxData);      
    
    
    });
    

    This allows everything to be loaded including styles and javascript, given that the script name and css file name are the same.

    0 讨论(0)
  • 2021-01-23 04:48

    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?

    0 讨论(0)
  • 2021-01-23 04:51

    AFAIK, JQuery load cannot be synchronous.

    You can cet around this witha callback function.

    $(document.body).load('hasCookie.html', function(){
    //call styling script here
    });
    
    0 讨论(0)
  • 2021-01-23 04:53

    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.

    0 讨论(0)
提交回复
热议问题