zondag 17 mei 2009

Creating a PHP Loading screen

Here is an example of how you can add a loading screen to your PHP page.

The main reason for doing this is when your PHP code will take a long time when executing. Things that will slow your code down enough to consider using a loading screen:
  • Use of external websites (ie. you are posting user data to Youtube, Myspace, Google ea.)
  • A server script that is executed (however you might want to use an AJAX loader when this happens)
What we will be doing is using the PHP command flush() to send the loading screen already, while the user is waiting for the page to render.
We will also be using the flush() command to post javascript that updates the loading screen.
We will be using the jquery library to enhance browser support.

Download the code as a zip-file

Click here to see a live example

Note that you can use the parts individually. So here is the source:

loadingscreen.php



<?php

function LoadingScreen_create( )
{
require_once 'loadingscreen.html';
flush();
}

function LoadingScreen_setPercentage( $percent )
{
?><script type="text/javascript">
LoadingScreen_setPercentage( '<?=$percent?>' );
</script><?php
flush();
}

function LoadingScreen_hide( )
{
?><script type="text/javascript">
LoadingScreen_hide( );
</script><?php
}

?>


loadingscreen.html



<link type="text/css" rel="stylesheet" href="loadingscreen.css" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="loadingscreen.js"></script>

<div id="loading-screen">
<div class="title">
<h1>Loading...</h1>
</div>
<div class="percentage">
<p>0%</p>
</div>
</div>


loadingscreen.js




LoadingScreen_setPercentage = function( percent )
{
$( '#loading-screen' ).find( '.percentage' ).html( percent + '%' );
}

LoadingScreen_hide = function( )
{
$( '#loading-screen' ).fadeOut( 'slow' );
}


loadingscreen.css



#loading-screen
{
position:fixed;
left:0px;
top:0px;
background-color:white;
height:100%;
width:100%;
}

#loading-screen .title
{
font-family: "URW Chancery L", "Apple Chancery", "Monotype Corsiva", "Georgia", serif;
font-size: 44.8px;
text-align: center;
}

#loading-screen .percentage
{
font-family: "URW Chancery L", "Apple Chancery", "Monotype Corsiva", "Georgia", serif;
font-size: 44.8px;
text-align: center;
}

Geen opmerkingen:

Een reactie posten