开发者

Loading page content and its CSS dynamically - how to prevent jump because CSS is not loaded yet?

开发者 https://www.devze.com 2023-02-15 07:22 出处:网络
On my website, I catch clicks on links to load the content of that page dynamically using AJAX. This new content may require some CSS file that isn\'t loaded yet. Setting the content of the target ele

On my website, I catch clicks on links to load the content of that page dynamically using AJAX. This new content may require some CSS file that isn't loaded yet. Setting the content of the target element to the response HTML will automatically load the required CSS (the <link> tags are there), but the content will look messed up for a brief period until the CSS gets loaded.

Other than loading all CSS files in advance, what can I do to prevent this? For completeness sake, here is my code:

$(document).ready(function() {

    $('a').live('click', function(event) {
        if (this.target || this.rel == 'ignore' || this.rel == 'fancybox') {
            return true;
        }

        if (/^javascript:/.test(this.href)) {
            return true;
        }

        if (this.href.indexOf('#') >= 0) {
            return false;
        }

        if (!this.href) {
            return true;
        }

        loadDynamicPage(this.href);
        event.preventDefault();
        return false;
    });
});

var currentLoader = null;
function loadDynamicPage(url) {
    if (currentLoader) {
        currentLoader.abort();
        currentLoader = null;
    }

    $('#backButton').addClass('loaderBG');
    currentLoader = $.ajax({
        context: $('#army_content'),
        dataType: 'text',
        url: url + '&format=raw',
        success: function(data) {
            currentLoader = null;
            $('#backButton').removeClass('loaderBG');
            clearRoomIntervals();

            $(this).html开发者_StackOverflow中文版(data).find('[title]').tooltip({
                showURL: false,
                track: false,
                delay: 300
            });

            $(document).trigger('dynamicLoad');
        }
    });
}


  1. Click on the link, show "Loading.."
  2. Load CSS file by ajax, in callback function, create <style> tag, and then insert CSS code to <style> tag, and then start load content by ajax.

*you can optimize the flow by load CSS and content individually, but content only take place in a hidden container, once CSS file finish load, then change hidden container to be shown.

Hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消