How to preload images on refresh? - html

I have a code, which gets refreshed from mysql database on a button click.
From the mysql I get links of images on refresh, but I never know, hat links and how many.
I have a "loading" circle which spins until the page is loaded, but it is shown only, until the code is loaded, which is not very long. After that I see small empty squares on my page as placeholders, until the real images show up.
Does anybody have an idea, how to show the spinning circle untill all images are loaded?
I tried some javascript examples found on the net with building arrays of links, but I was not able to integrate them into my code, because the construction of the codes are very different and I obviously am not a pro.
So here is my code (I simplified it for now):
$(document).ready(function() {
function refresh(free){
$("#loadingfree").show();
if (free) datum = datum + free;
var url = "listfree.php?date=" + datum;
$.getJSON(url,function(data) {
var div_data = '';
$.each(data, function(i,data) {
div_data += "<div class='iconsfree'><a href='"+data.title+"-"+data.appID+"' title='"+data.title+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#loadingfree").hide();
$("#app-wrapper-free").html(div_data);
});
}
$(document).on('click', '#prevbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(-1);
});
$(document).on('click', '#nextbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(+1);
});
// call the method when page is opened:
refresh(0);
});

If you want the spinner to continue showing until the images are loaded, you should use the load eventListener to make that happen.
So let's say you have your code that has the spinner while it makes the request to the server.
//just an example
$('button').click(function(){
//call server
$.ajax();
//show spinner
$('.spinner').show();
});
Now we will tell the spinner to stay showing until the images are done loading.
$('img').on('load',function(){
//Not sure what your spinner is called
$('.spinner').hide();
});

I ended up with this.
It just shows the content a bit later. It's a fake preloader.
<script type="text/javascript">
var datum = 0;
$(document).ready(function() {
function refresh(free){
if (free) datum = datum + free;
var url = "listfree.php?date=" + datum;
$.getJSON(url,function(data) {
var div_data = '';
$.each(data, function(i,data) {
if ($("#date_free").html() == '');
div_data += "<div class='iconsfree'><a href='"+data.title+"-"+data.appID+"' title='"+data.title+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#loadingfree").show();
$(div_data).hide()
.appendTo("#app-wrapper-free")
setTimeout( function() {
$("#app-wrapper-free").children().show()
$("#loadingfree").hide()
}, 3000 );
});
}
$(document).on('click', '#prevbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(-1);
});
$(document).on('click', '#nextbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(+1);
});
// call the method when page is opened:
refresh(0);
});
</script>

Related

Are there possibilities to change a mobile page smoothly and without jqm?

I am creating a Phonegap app and I really want to avoid jqm in the project, because the css is just blowing up the whole html code. So I can change the pages with
window.location = "profiles.html";
but that's a pretty hard cut in the user experience and I really want to change this to something more smooth. Are there any possibilities to enhance the changepage process, maybe with css or something?
You can use a fade effect.
var speed = 'slow';
$('html, body').hide();
$(document).ready(function() {
$('html, body').fadeIn(speed, function() {
$('a[href], button[href]').click(function(event) {
var url = $(this).attr('href');
if (url.indexOf('#') == 0 || url.indexOf('javascript:') == 0) return;
event.preventDefault();
$('html, body').fadeOut(speed, function() {
window.location = "profiles.html";
});
});
});
});
See it in action (jsFiddle)

Refreshing a div using .load() function

$(document).ready(function(){
$('#container').load('contents/home.html');
$('#nav ul#navigation li a').click(function(){
var page = $(this).attr('href');
$('#container').fadeOut('slow').load('contents/' + page + '.html').fadeIn('slow');
return false;
});
});
This works good when loading pages within a div container.
home.html containing nivoSlider, when the whole page is refreshing it works good but loading home.html again onto #container after loading pages using function
$('#container').load('contents/' + page + '.html') then the nivoSlider isn't not working.
I have to refresh the whole page just to refresh the div. So I need a code to refresh the div every time it load the pages onto the div #container.
Make sure to encapsulate unique knowledge in a single place in your code. If you need to refresh something, make sure to put this in a single place and then call it as required. Your code could look something like this:
$(document).ready(function() {
var container = $('#container');
function loadContent(url, callback) {
return container.load(url, {}, function () {
// Add code here to refresh nivoSlider
// Run a callback if exists
if (callback) {
callback();
}
});
}
loadContent('contents/home.html');
$('#nav ul#navigation li a').click(function (event) {
var page = $(this).attr('href');
container.fadeOut('slow').loadContent('contents/' + page + '.html').fadeIn('slow');
event.preventDefault();
});
});

JqueryMobile Cache Ajax issue

I have a strange issue with my jquery mobile application. Below screen shot from Chrome Developer Tools Snapshot.
Why does my Pages or Scripts are cached even thiugh Have added
$.ajaxSetup ({
cache: false
});
Also in every ajax call which loads my ul > li have set cache:false.
Kindly let me know how can I overcome this scenario coz of this my Mobile cache is growing on every single click driving me nuts.
Thanks
Update :
Every time I click to navigate to another page this scripts get executed :
$('body').on('click', '.menuClass', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var menuid = $(this).attr('id');
if (menuid == '100001') {
settings.get('setval', function(obj) {
if(obj.value.tableMode == "1"){
$.mobile.changePage('categories.html', {
transition : "slide"
});
return false;
}
else{
$.mobile.changePage('index.html', {
transition : "slide"
});
}
});
}
});
But for somereasons the URL for categories.html loads on every click changing the url to
below
http://localhost:8080/categories?_=1347279588477
http://localhost:8080/categories?_=1347279584203
http://localhost:8080/categories?_=1347279688227
I don't know why cache:false doesn't work but i'm adding a time created string to prevent caching of ajax pages.
Doing this by adding &ts="+ new Date().getTime() to end of url .
Here is my usage ;
$.ajax({
type: "GET",
url: "ajax.php?ajax_file=ajax_table_page&ts="+ new Date().getTime(),
success: function(data){
..................
}
});
I also use this to trace ajax errors (you may add after document is ready )
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});

dojo 1.8 integrating html5 postmessage

Im trying to get some html5 post messaging going with dojo 1.8, i've created a jsfiddle to try to explain it better. One thing to note is that the button is being loaded within the iframe. So basically if a click happens within the iframe then the parent node should receive and act upon the message. Any pointers would be appreciated.
http://jsfiddle.net/AvPFv/
Basically, you should listen for message on iframe window, i.e. iframe.contentWindow. Also, please note there is no dojo in your iframe.
I created a jsFiddle to show how it works: http://jsfiddle.net/phusick/H7Zh8/ but I'm afraid it is very messy to have everything in a single file, i.e. in the context of the parent window, because it does not explain properly where window reference points to and it does not simulate real world usage. I suggest you try it at localhost having two sets of scripts, one for parent window and one for iframe.
require([
"dojo/dom",
"dojo/on",
"dojo/date/locale",
"dojo/domReady!"
], function(
dom,
on,
locale
) {
var buttonNode = dom.byId("postMessageButton");
var iframeNode = dom.byId("iframe");
var iframe = iframeNode.contentWindow;
var iframeButtonNode = iframe.document.getElementById("postMessageButton");
on(buttonNode, "click", function() {
iframe.postMessage("hello from parent", "*");
});
on(iframe, "message", function(event) {
var msgNode = iframe.document.getElementById("msg");
msgNode.innerHTML += formatMessage(event);
event.source.postMessage("echo from iframe", "*");
});
on(iframeButtonNode, "click", function() {
iframe.parent.postMessage("hello from iframe", "*");
})
on(window, "message", function(event) {
dom.byId("msg").innerHTML += formatMessage(event);
});
function formatMessage(event) {
var time = locale.format(new Date(event.timeStamp),{
selector: "time",
formatLength: "medium"
});
return time + ": " + event.data + "<br>";
}
});

How to put loading in mootools?

now i want create slideshow banner with mootools and i want to put loading image, mean after all images is loaded then start show all images (with slideshow).
My question is how to put LOADING ?
here my code :
<script type="text/javascript" src="js/mootools-1.2.4.js"></script>
<script type="text/javascript">
window.addEvent('domready',function() {
/* settings */
var $xxa = jQuery.noConflict();
var showDuration = 3000;
var container = $('slideshow-container');
var images = container.getElements('img');
var currentIndex = 0;
var interval;
/* opacity and fade */
images.each(function(img,i){
if(i > 0) {
img.set('opacity',0);
}
});
/* worker */
var show = function() {
images[currentIndex].fade('out');
images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0].fade('in');
};
/* start once the page is finished loading */
window.addEvent('load',function(){
interval = show.periodical(showDuration);
});
});
</script>
have a look at the mootools-more Asset.images from Asset.js
it can load multiple images and it fires onprogress / oncomplete events for the lot. http://mootools.net/docs/more/Utilities/Assets#Asset:Asset-images
what you do implies the images have loaded already - the load will trigger after all is done if they are in the dom - but it will wait for other elements as well as your images of interest, so that's a little wasteful
you can still create a new Element on domready saying 'loading' and destroy it onload, keep your code as is.
eg.
var loader = new Element("div", {
html: "loading..."
tween: {
onComplete: function() {
this.element.destroy();
}
}
}).inject(document.id("sometarget"));
...
window.addEvent('load', function(){
loader.fade('out'); // will fade and destroy it.
interval = ...
});