I’ve come to the conclusion that there’s just one best practice for loading JavaScript without blocking:
1. Create two JavaScript files. The first contains just the code necessary to load JavaScript dynamically, the second contains everything else that’s necessary for the initial level of interactivity on the page.
2. Include the first JavaScript file with a tag at the bottom of the page, just inside.
3. Create a second tag that calls the function to load the second JavaScript file and contains any additional initialization code.
A helper to make this happen could look like:
function loadScript(url, callback){ var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }In related news, the LABjs folk have updated their API from this:
$LAB .script("jquery.js") .block(function(){ $LAB .script("jquery.ui.js") .script("myplugin.jquery.js") .block(function(){ $LAB.script("initpage.js"); }); });To the simpler:
$LAB .script("jquery.js") .block() .script("jquery.ui.js") .script("myplugin.jquery.js") .block() .script("initpage.js");I seem to remember that Steve had some opinions on this API too :)
If you have better solution, just tell me !
AJAX, PHP and Javascript Errors
Javascript is a powerful tool in the web programmers toolbox however, it's also one of our greatest headaches. Dealing with browser inconsistencies is always a source of great pain. You test on multiple platforms, find everyone you know with a mac running safari and think you have your code locked down however it rarely always works out this way. Being able to detect javascript errors in the wild can be a great resource for you to really see how your code is performing on a day to day basis. Mozilla and IE support a powerful event handler called "onerror" used like window.onerror = function(){};
You can create a custom function at the top of all your scripts that will record any parsing or exception errors generated. You can create your function to accept 3 parameters, the message of the error, the URL of the error and the Line number of the error. Creating this function is as simple as so:
<SCRIPT>
window.onerror = function(msg, err_url, line) {
alert('an error occured on line: ' + line);
}
</SCRIPT>
Now the end user really doesn't care which line an error occurred on but the powerful part is being able to get this information back to the developers. Using AJAX technologies you can easily record a log of all js errors on your site so you can take appropriate action to fix these issues. Not only can you include msg, line and error URL, but you can also send any other information javascript can capture such as referring page and the type of browser the client is using.
// post data you want to send to the server
var POSTData = 'msg=' + msg ;
// create the actual xmlhttprequest object and pass the URL of the PHP page you want to call
var s = new XMLHTTP("error_server.php?");
// post data to the server and assign processReqChange as the function to call back when the data is posted
var xmlDoc = s.call(POSTData, processReqChange);
Putting these two things together you can now log all of your JS error msgs behind the scenes and create an offline viewer that you and your other programmers can sift through. I prefer to err on the side of performance so the goal is just to log some quick info to the server and set up a cron job to email that data each night to the developers.
FILE 1 - Our main HTML File index.html.So what we're doing here is first including our XMLHTTPRequest class to instantiate our JS Object, then including the onerror functionality that will log the data to our server on every webpage.
If you have better solution, just tell me !
E-mail Validation With Javascript
The function below checks if the content has the general syntax of an email.
This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign:
function validate_email(field,alerttxt)
{
with (field)
{
apos = value.indexOf("@");
dotpos = value.lastIndexOf(".");
if (apos<1dotpos - apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}The entire script, with the HTML form could look something like this:
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false;}
}
}
</script>
</head>
<body>
<form action="submit.htm"
onsubmit="return validate_form(this);"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>If you have better solution, just tell me !
Form Validation using jQuery
Let us start with a simple example. Our demonstration form contains four fields: name, e-mail, comment and URL. As you can see, the first three fields are required, whereas the URL field is optional. If you submit the form without filling in the required fields, you will be prompted with an error message.
Here is the code we used for the form in the demonstration above.The code is quite straightforward and doesn't need much explanation. However, there are a few important points that I would like to bring to your attention.
<html>
<head>
<title>Simple Form Validation</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/
validate/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required",// simple rule, converted to {required:true}
email: {// compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
input[type=text], textarea { width: 250px; float: left; }
textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL</span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
</form>
</body>
</html>
Now, let us see the validate() function in detail.All we are doing here is initializing the validation of the form using the validate() function. It can take several parameters. In the example above, we use only two of them, but you can find a list of all the options for the validate() function at :
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", // simple rule, converted to {required: true}
email: { // compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
You can find an exhaustive list of built-in validation methods at Demo
If you have better solution, just tell me !Time and Date difference using a PHP function
This is a simple PHP function dateTimeDiff() written for an application that I am developing, useful to get time and date difference between two date (a reference date and "now"), with a Digg-like style (ex: 12 min 20 sec ago). The mask of reference for each date is 2007-10-18 20:05:22, a standard MySQL datetime field.
Download Sample Code
How it works?
First, you have to include the file time Function.php into the PHP file that will use the function.
<?php include('timeFunction.php') ?>... and you have to pass the data which it goes made the comparison:
dateTimeDiff($dataRef);... where $dataRef is, for example, a value from a SQL query.
The codeThis is the code of dateTimeDiff() PHP function:If you have better solution, just tell me !
<?php function dateTimeDiff($data_ref){
// Get the current date
$current_date = date('Y-m-d H:i:s');
// Extract from $current_date
$current_year = substr($current_date,0,4);
$current_month = substr($current_date,5,2);
$current_day = substr($current_date,8,2);
// Extract from $data_ref
$ref_year = substr($data_ref,0,4);
$ref_month = substr($data_ref,5,2);
$ref_day = substr($data_ref,8,2);
// create a string yyyymmdd 20071021
$tempMaxDate = $current_year . $current_month . $current_day;
$tempDataRef = $ref_year . $ref_month . $ref_day;
$tempDifference = $tempMaxDate-$tempDataRef;
// If the difference is GT 10 days show the date
if($tempDifference >= 10){
echo $data_ref;
} else {
// Extract $current_date H:m:ss
$current_hour = substr($current_date,11,2);
$current_min = substr($current_date,14,2);
$current_seconds = substr($current_date,17,2);
// Extract $data_ref Date H:m:ss
$ref_hour = substr($data_ref,11,2);
$ref_min = substr($data_ref,14,2);
$ref_seconds = substr($data_ref,17,2);
$hDf = $current_hour-$ref_hour;
$mDf = $current_min-$ref_min;
$sDf = $current_seconds-$ref_seconds;
// Show time difference ex: 2 min 54 sec ago.
if($dDf<1){
if($hDf>0){
if($mDf<0){
$mDf = 60 + $mDf;
$hDf = $hDf - 1;
echo $mDf . ' min ago';
} else {
echo $hDf. ' hr ' . $mDf . ' min ago';
}
} else {
if($mDf>0){
echo $mDf . ' min ' . $sDf . ' sec ago';
} else {
echo $sDf . ' sec ago';
}
}
} else {
echo $dDf . ' days ago';
}
?>Email syntax validation using javascript
We should validate the syntax of email entered in the form in the client side itself to save unnecessary server process to validate the email.It can be done using javascript. Consider below form. onSubmit event of Form is calling a javascript function ValidateForm .
<form name="frmSample" method="post" action="" onSubmit="returnValidateForm();">
<p>Enter an Email Address :
<input type="text" name="txtEmail">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>The javascript function ValidateForm is calling another function emailcheck to validate syntax of the email id.
<script language = "Javascript">
function emailcheck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
return false //if @ symbol is not there
}
if (str.indexOf(at)==-1 str.indexOf(at)==0 str.indexOf(at)==lstr){
return false //if @ symbol available at starting or ending of email.
}
if (str.indexOf(dot)==-1 str.indexOf(dot)==0 str.indexOf(dot)==lstr){
return false //if "." is not available,or available at beginning or end of email.
}
if (str.indexOf(at,(lat+1))!=-1){
return false //if more one @ symbol available in email
}
if (str.substring(lat-1,lat)==dot str.substring(lat+1,lat+2)==dot){
return false //if no letter is available between @ and "."
}
if (str.indexOf(dot,(lat+2))==-1){
return false
}
if (str.indexOf(" ")!=-1){
return false //if blank space available in email.
}
return true
}
function ValidateForm(){
var emailID=document.frmSample.txtEmail
if ((emailID.value==null)(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (emailcheck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
</script>If you have better solution, just tell me !
Date validation in javascript
The method below will valdiate a date.
This will not take care for 29 Feb or 30 Feb or 31 Feb
It is a basic date valdiation.
function checkDate(input) {
var validformat = /^(0[1-9]1[012])[-](0[1-9][12][0-9]3[01])[-](1920)\d\d+$/;
var returnval = true;
if (!validformat.test(input)) {
alert("The specified delivery date is invalid. Please specify the date in the proper format(MM-DD-YYYY) to continue.");
returnval = false;
}
return returnval;
}
If you have better solution, just tell me !