Preload AJAX images/content in Wordpress - javascript

I'm currently using AJAX to load my Wordpress posts into the Index page once the title is clicked—like an accordion. The problem is, most of the posts contain lots of large images and it's taking a long time for them to show once the AJAX function has run and all you see are the image captions stacked up before the images start loading.
Is there a way that I can preload the content that is being added by AJAX, so when the user clicks the title the images load super quick?
Below is the AJAX code I am using. All help is greatly appreciated. Thanks in advance!
$("a.exhibitionInformation").on("click", function(event) {
var exhibitionContainer = $(this).parent(".exhibition");
var url = $(this).attr("href");
var doc = $(this).next(".exhibitionDocuments");
var title = convertToSlug($(this).text().split("\n")[1]);
var slug = $(this).attr("data-slug");
$(this).toggleClass("selected");
if($(doc).is(':not(:hidden)')) {
$(doc).slideToggle();
} else {
$.ajax({
url: url,
type: "GET",
success: function(data) {
var content = $(data).find(".single-document");
$(doc).append(content).slideToggle(300);
$("html, body").animate({ scrollTop: exhibitionContainer.offset().top - 26 });
window.location.hash = slug;
}
});
}
event.preventDefault();
});

Related

Prioritise XHR requests over images?

I'm doing some basic ajax requests for changing pages, example:
$(document.body).on('click', ".paging a", function (e) {
$.ajax({
type: "GET",
url: $this.attr('href'),
success: function (data) {
$("#main-content").html(data);
}
});
e.preventDefault();
return true;
});
The URL the ajax request calls to returns HTML, sometimes this HTML contains 30-40 <img> images.
The problem I'm hitting is if you click two pages in quick succession there is a delay while the browser waits until it has loaded all the images in the HTML of the previous ajax request until it makes the next XHR call.
Is there a way to prioritise the XHR request ahead of the images? Basically if another page is clicked I want all current requests to stop and the XHR request to execute immediately. As far as I've seen this is occurring because browsers have a limit to how many asynchronous requests it'll make to one domain (i.e. 6 for chrome) and if I changed the images to use a sub-domain it would probably fix it, but I'm trying to find a way to do it without having to resort to sub-domains.
Using XMLHttpRequest you can load images and abort.
var xhrAr = Array();
function abortXhr(){
for(var key in xhrAr)
xhrAr[key].abort();
xhrAr = Array();
}
function startXhr(dataObj){
var imgObj = dataObj.find('img');
imgObj.each(function(){
var thisObj = $(this);
var src = $(this).attr('src');
$(this).attr('src', ''); //prevent loading
var xhr = new XMLHttpRequest();
xhr.open("GET", src, true);
xhr.responseType = "blob";
xhr.onload = function(){
var imageUrl = (window.URL || window.webkitURL).createObjectURL(this.response);//Creating blob ul
thisObj.attr('src', imageUrl);
}
xhr.send();
xhrAr.push(xhr);
});
}
$(document.body).on('click', ".paging a", function (e) {
abortXhr(); //abort
$.ajax({
type: "GET",
url: $this.attr('href'),
success: function (data) {
var dataObj = $(data);
startXhr(dataObj);//Start
$("#main-content").append(dataObj);
}
});
e.preventDefault();
return true;
});
When the user clicks on a new page, you could
Store the html of "#main-content" element in a variable
Empty the all src attributes of tags in "#main-content"
Make your XHR request
Reset the settings of "#main-content"
This way the img http connections are aborted, the XHR request is fired and finally your image requests resume from where they were left. (this can vary on the cache settings for your images)
$('#goto-page-2').click(function (e) {
var mainContentHTML = $("#main-content").html();
$("#main-content").find('img').attr('src', ''); //clear images
$.ajax({
type: "GET",
url: $this.attr('href'),
success: function (data) {
}
});
$("#main-content").html(mainContentHTML); // reset images
e.preventDefault();
return true;
});
References
How to cancel an image from loading
In this case you are changing your page content and that content is having images so images is taking time. so in this case you can do one thing if you know which image you are using on those page then load them all images on main page when first time your page is loading.you can have these all image in a hidden div. and when your page content is changes that have these images then it will start showing very quickly becuase they are already in browser memory.

Can't load JSON when loading pages with Ajax and hash url

I'm currently working on a project using jQuery and Ajax to load in content from local html files to my single page site. I've also got a JSON file that I'm trying to incorporate into the files being loaded in with jQuery and Ajax.
I'm using hash urls to keep the pages separate. This is the code I'm using:
//other cached links
var pageLinks = $(".pageLink");
if(window.location.hash) {
var hash = window.location.hash.replace("#", "");
loadPage(hash + ".html");
} else {
loadPage("index.html");
}
pageLinks
.click(function(){
var iid = $(this).attr("id");
loadPage(iid + ".html");
});
function loadPage(resource) {
window.location.hash = resource.replace(".html", "");
$.get("pages/" + resource, function (data) {
content.html(data);
});
}
//this makes sure the contents of hash in the url is loaded in the page
if(window.location.hash) {
var hash = window.location.hash.replace("#", "");
loadPage(hash + ".html");
} else {
loadPage("index.html");
}
This is how I'm putting my JSON data into the page:
function FooBar() {
this.foo;
this.barLinkTemplate;
}
var fooBar = new FooBar();
$(document).ready(function (){
fooBar.contentDiv = $("#fooContent");
fooBar.barDiv = $("#bars");
$.when(
$.getJSON('data/music.json'),
$.ajax('components/components.html')
).done( function(data, templateData) {
var templateHTML = $(templateData[0]);
fooBar.barLinkTemplate = Handlebars.compile( templateHTML.find("#barLinks").html() );
fooBar.data = data[0].foo;
fooBar.barDiv.html( fooBar.barLinkTemplate( data[0].bars ));
));
});
The Ajax loads just fine, hashes and all. However, nothing from my JSON file is loaded into the page. I think I've narrowed my problem down (at least I hope) to one bit of code. If I comment out the last if/else statement (above), the JSON is loaded in the first page (only the first page). If I click on any link, and I navigate back to that page, the JSON data is gone. I have to actually reload the page for the data to reappear.
Without that if/else statement, I lose the ability to load the page content from the hash in the url--though the links still work fine.
I've been googling, but I haven't seen anything similar to the problems I'm having. Any help is appreciated. Thanks!

new ajax request on scroll

this is javascript
$(window).scroll(function() {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function my_func () {
//show new name
}
});
});
this is not_data.php
<?php
$name_query=mysql_query("SELECT name FROM names");
while($run_query = mysql_fetch_assoc($name_query)) {
$name = $run_query['name'];
echo $name;
}
?>
i want to call a new ajax request and get a new name from table names everytime user scrolls down
have a look at this excellent jquery plugin!
http://jscroll.com/
jScroll is a jQuery plugin for infinite scrolling, written by Philip
Klauzinski. Infinite scrolling; also known as lazy loading, endless
scrolling, autopager, endless pages, etc.; is the ability to load
content via AJAX within the current page or content area as you scroll
down. The new content can be loaded automatically each time you scroll
to the end of the existing content, or it can be triggered to load by
clicking a navigation link at the end of the existing content.
creat param for check loading state;
bind to scroll event
get two params
var top = $(this).scrollTop();
var height = $(this).height();
check scroll height
if (elHeight - top - height <= 50)
where elHeight - height of all element
and when it's true do your query
Try like this.
$(window).scroll(function() {
if( $(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function (res) {
// new name will be available in 'res' you can display in what way you like.
}
});
}
});
Check If you have reached bottom and load more(send ajax call)
var win = $(window),
doc = $(document);
win.scroll(function(){
if( win.scrollTop() > doc.height() - win.height() ) {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function my_func (name) {
$('<span>').html(name).appendTo('body')
}
});
}
});

jQuery/Javascript: HTML pulled in by AJAX request does not include <script> elements

I have a dynamic page which uses an AJAX request kicked off by jQuery to pull in HTML elements from the server and insert them into the DOM.
The problem is that when I have elements within the response, they are stripped out.
For instance, if I request the following from the server:
<!-- content.html -->
<div>
There is some content here!
<script>
manipulateContent();
</script>
</div>
What actually gets injected into my dynamic page is the following:
<!-- content.html -->
<div>
There is some content here!
</div>
I have tested in Chrome, Firefox, and Safari with identical results.
The relevant Javascript which creates the AJAX request is here:
function loadContent(url){
var a = document.createElement('a');
a.href = url;
if (a.search == ""){
url = url + "?trim=true";
} else {
url = url + "&trim=true";
}
var ch = $('#content-container').height();
// var wh = $(window).height();
$("#content").animate({top: '-='+ch+'px'}, 500, function(){
$.get(url, function(data){
$("body").scrollTop(0);
$("#content").html(data);
$("#content").css({top: ch+'px'});
$("#content").animate({top: '0px'}, 500);
});
});
}
$(document).ready(function(){
// get the current path and save it for later
var currentPage = location.pathname+location.search;
$(".content-link").live("click", function(){
// using the HTML5 history API, add the requested path
// to the browser history, then load the new content
history.pushState({ path: this.path }, '', this.href);
// because the page is not reloaded, $(document).ready()
// is not called, so the currentPath must be updated manually
currentPage = this.href;
loadContent(currentPage);
return false;
});
window.addEventListener('popstate', function() {
// compare the current path to the one being loaded
// if they are different, then load the content
// else, nothing happens
if (currentPage != location.pathname+location.search){
// because the page is not reloaded, $(document).ready()
// is not called, so the currentPath must be updated manually
currentPage = location.pathname+location.search;
loadContent(currentPage);
}
});
});
How can I tell jQuery to include the tags in the response? I've tried browsing through the jQuery docs without much luck, or even mention of the fact that the tags are stripped out. Perhaps I'm just not looking in the right places.
You need to use load, since the whole purpose here is to load hml content to a element.
function loadContent(url) {
var a = document.createElement('a');
a.href = url;
if (a.search == "") {
url = url + "?trim=true";
} else {
url = url + "&trim=true";
}
var ch = $('#content-container').height();
// var wh = $(window).height();
$("#content").animate({
top : '-=' + ch + 'px'
}, 500, function() {
$("#content").load(url, function() {
$("body").scrollTop(0);
$("#content").css({
top : ch + 'px'
});
$("#content").animate({
top : '0px'
}, 500);
});
});
}
According to jQuery documentation (http://api.jquery.com/jQuery.ajax/) if dataType option is html:
Returns HTML as plain text; included script tags are evaluated when
inserted in the DOM.
By default this option is set to Intelligent Guess, so you may want to check the type of response from the server.

Pre load images from an ajax request before displaying them?

I'm using jQuery to load html content which contains images, the problem is that i don't want the effect of blinking on images due to loading, to achieve that i need to pre load images inside the response body before inserting it to guarantee a smooth update.
Current Code:
$.ajax({
url: 'hello.php',
method: 'GET',
data:'id='+id,
success: function(data) {
$('#section').html(data);
}
});
Any Solutions?
Thanks
I use the the jQuery onImagesLoad plugin for this.
You could try something like this (untested):
var imagesLoading = 0;
$.ajax({
url: 'hello.php',
method: 'GET',
data: 'id=' + id,
success: function(data) {
imagesLoading = 0;
$(data).filter('img').each(function() {
imagesLoading++;
var image = new Image();
image.onload = function() {
imagesLoading--;
if(imagesLoading == 0) {
$('#section').html(data);
}
};
image.src = $(this).attr('src');
});
}
});
Works fine when I tried it.

Categories