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');
}
});
}
- Click on the link, show "Loading.."
- 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.
精彩评论