Reputation: 2259
I have a script that loads pages via ajax for users with custom URLs. For example, a profile is typically located at http://example.com/users/Dan but if a user has a custom URL, say, http://example.com/DansCustomURL, then I need to fetch their desired target URL (in this case the user's profile /users/Dan).
Once the HMTL has been fetched and loaded into the data
parameter, the content appears immediately, but the CSS styling and some images etc. take a bit longer causing the page to look broken until they are loaded.
Is there anyway to detect when all the elements located in the data
variable have been loaded?
My HTML and inline Javascript/jQuery/Ajax is below.
<omni>
<script type="text/javascript" src="assets/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function() {
var rewritePath = '/users/Dan';
$.get(rewritePath, function(data,status) {
$('.hidden-element').append(data).onDataElementsLoad(function() {
$(this).fadeIn();
});
});
});
</script>
<div class="hidden-element"></div>
</omni>
Of course .onDataElementsLoad()
is not a real method, but this is what I'm looking to do.
I'm familiar with the waitForImages
plugin, but I was hoping to not need another dependency for this (seemingly) simple task.
An example can be seen at https://merkd.com/url.php?url=dan
I was going to post a fiddle, but it wouldn't allow me to use an external link in that way.
(A preloader will be added in the future, but the issue of preloading for the images in data
would still exist.)
I tried the .done()
method as instructed by another user in an answer below, but it does not prevent the page from appearing broken before styling/images are loaded.
This is the code I'm using now, and as you can see, the example still page still has a delay in styling/loading elements after the content itself appears.
var rewritePath = '/u/dan';
$.get(rewritePath).done(function(data) {
console.log('loaded');
$('omni').after(data).remove();
});
Upvotes: 1
Views: 48
Reputation: 139
What about:
$.get( "test.cgi", { name: "John", time: "2pm" } )
.done(function( data ) {
alert( "Data Loaded: " + data );
});
.done is callback for success load content from ajax in $.get function.
Upvotes: 1
Reputation: 209
No need for ajax. You can do something like this
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img).fadeIn(50);
}
});
Upvotes: 0