0

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(data).find('[title]').tooltip({
                showURL: false,
                track: false,
                delay: 300
            });

            $(document).trigger('dynamicLoad');
        }
    });
}
Aistina
  • 12,435
  • 13
  • 69
  • 89

1 Answers1

0
  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.

ahgood
  • 1,847
  • 20
  • 19
  • What would you use to extract the URLs to the CSS files from the AJAX response? Regex? – Aistina Mar 08 '11 at 14:43
  • I tried what you said, but putting the contents of the CSS file in a – Aistina Mar 08 '11 at 15:13
  • Then you can update the background image path in your CSS file like this: /images/abc/background.gif (starts with /) – ahgood Mar 09 '11 at 00:36