Reputation: 55
I was wondering if there exists a carousel which has a bunch of images shown to the user, but lets say that based on the User, the img shown in the carousel needs to change to something else. How can one change the img src, even before the page loads? The DOM does not actually exist for us to get the dom element for img element and change its src to the new image? how can one do it?
I was thinking may be have a inline script tag within the head section where the async is set to false which does not block the loading of the DOM. I am not sure. Please let me know if there are any other alternatives or html5 features for this
Upvotes: 0
Views: 1544
Reputation: 419
It doesn't make much sense to literally "change" the source before the DOM loads, otherwise why did you set that source to begin with, right? But as others are saying, Javascript will be executed the moment it comes to the browser, so if you are having the image sources loaded as per any session criteria, etc. etc., you could use the event that when the page is loaded, to perform any particular AJAX requests, e.g. using jQuery:
$(document).ready(function() {
$.ajax({
url: '/getPhotos',
success: function(res) {
res = JSON.parse(res);
for (var i in res) {
$('ul#carousel').append('<li><img src="'+res[i].src+'" /></li>');
}
}
});
);
Something like what you are after?
Upvotes: 0
Reputation: 88
You can't use JavaScript to access the DOM before it is loaded. The best way to deal with this is to compile your HTML on the server-side using a templating language like handlebars (depends on what your backend language is). However, if this isn't an option you could also just put a place-holder loading symbol in the place of your image and then dynamically add a src url once your <img>
has loaded in the DOM and then use JS or jQuery to change the src
attribute.
Hope that helps!
Upvotes: 1