Posts Tagged ‘OpenSource’

5 ways to use Ajax with jQuery

Tuesday, August 25th, 2009

The people of Nettuts publishes an interesting article on using  jQuery with Ajax. Specifically the 5 ways that jQuery allows us to send asynchronous requests.

  • $.load()
  • $.get()
  • $.post()
  • $.getJSON()
  • $.getScript()

$. load ()

This is the feature I like most about jQuery already makes one of the most common tasks of developing with Ajax is as simple and straightforward as we shall see in this example:

$("#div_links").load("/Main_Page #jq-p-Getting-Started li");

This example brought to the documentation page on jQuery, it manages to launch a request to the URL /Main_Page (usa URL Rewrite) HTML response and take the #jq-p-Getting-Started li and inserted into #div_links
Just great, comfortable and fast.

$. get ()

This is the simple function with which we can launch the server via GET requests Ajax.

$.get("test.cgi", { name: "Venu", time: "7pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

By passing 3 options, 2 of which are options (rather conditional) you can request to launch the file (1) with parameters (2) and treat the response through a callback (3rd).

$. post ()

Like the above, this feature lets you send POST requests using Ajax.

$.post("test.php", { name: "Venu", time: "7pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

As easy as above.

$. getJSON ()

Although the above are able to specify the type of return, the best option is to use this method to obtain the response in JSON evaludada the callback function.

$.getJSON("test.js", { name: "Venu", time: "7pm" }, function(json){
  alert("JSON Data: " + json.users[3].name);
});

Taking into account the browser, the object will use native JSON or use a system based on eval().

$. getScript ()

Although technically not an Ajax request is a request to the server and therefore has a place in the post.

$.getScript("test.js", function(){
  alert("Script loaded and executed.");
});

With this method we can load a file asynchronously using JavaScript and the parameter (2) callback can execute Javascript code that is using the js file that we want to load (1).

FTP connection with JAVA

Tuesday, August 25th, 2009

Java again gives us another tool.

What is FTP?

FTP protocol that allows us to send or receive data from one point to another, be it a PC, server, or any other node that is connected to a network.

Usually when you have a web host these accounts have FTP congratulate sending files from our pc to the server that is hosting our site.

Investigating around I found a FTP client library very useful, I have tried it and going great. The library JvFTP Client provides interesting tasks, including:

  • Uploading / downloading files
  • Uploading directories recursively
  • Concurrent data transfer
  • Data transfer mode passive / active
  • Swing components to display directories
  • Components AWTpara display directories

This tool is available in jvftp and can be used in two ways, you run directly the jar, or do your own programming, including the libraries in your project.

If you want to program your own example here I leave a little guide on how you can do, let’s see …

… The first thing to do is incorporate the packages downloaded from jvftp in your project. Then you import the libraries to the class in which you make the connection:

import cz.dhl.io.*;
import cz.dhl.ftp.*;
import java.io.IOException;

Now we create the connection, the connection to prepare the data before creating access the FTP site. Let’s start with the server:

FtpConnect cn = FtpConnect.newConnect("ftp://ftp.domain.com");

ftp.domain.com value which is the server you are connecting. Each ftp account that include at least the server name, username and password. To log in using that account is something like this:

// Username
cn.setUserName("username");

// Password
cn.setPassWord("password");

Then it creates an object of type FTP, which is responsible for rendering all the information from our FTP site.

Ftp ftp1 = new Ftp();

Now the connection to the FTP site to begin processing the respective tasks

ftp1.connect(cn);

A practical example to test the connection would be to show the current directory with their files:

CoFile dir = new FtpFile(ftp1.pwd(), ftp1);

// Make a list of files that have the current directory
CoFile cfls[] = dir.listCoFiles();
if ( cfls != null )
        for (int n = 0; n < cfls.length; n++)
                    System.out.println( cfls[n].getName() + (cfls[n].isDirectory() ? "/" : ""));

Finally, there is only close the connection.

ftp1.disconnect();

Download jvftp

Happy Programming!!! ;-)

Code in C# to create a backup of a database in SQL server and restore it

Wednesday, August 19th, 2009

Here they left a code in C # very useful when making your applications with databases in SQL server can support the database and restore it.

Support code for a button:

private void btnBackUp_Click(object sender, EventArgs e)
{
    bool bBackUpStatus = true;

    Cursor.Current = Cursors.WaitCursor; 

     if (Directory.Exists(@"c:\SQLBackup"))
        {
            if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
            {
                if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    File.Delete(@"c:\SQLBackup\wcBackUp1.bak");
                }
                else
                    bBackUpStatus = false;
            }
        }
        else
            Directory.CreateDirectory(@"c:\SQLBackup");

        if (bFileStatus)
        {
            //Connect to DB
            SqlConnection connect;
            string con = "Data Source = localhost; Initial Catalog=dbWiseCodes ;Integrated Security = True;";
            connect = new SqlConnection(con);
            connect.Open();
            //----------------------------------------------------------------------------------------------------

            //Execute SQL---------------
            SqlCommand command;
            command = new SqlCommand(@"backup database dbWiseCodes to disk ='c:\SQLBackup\wcBackUp1.bak' with init,stats=10", connect);
            command.ExecuteNonQuery();
            //-------------------------------------------------------------------------------------------------------------------------------

            connect.Close();

            MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
}

Code for a button to restore:


private void btnRestore_Click(object sender, EventArgs e)
{

    Cursor.Current = Cursors.WaitCursor;

    try
    {
        if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
        {
            if (MessageBox.Show("Are you sure you restore?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //Connect SQL-----------
                SqlConnection connect;
                string con = "Data Source = localhost; Initial Catalog=master ;Integrated Security = True;";
                connect = new SqlConnection(con);
                connect.Open();
                //-----------------------------------------------------------------------------------------

                //Excute SQL----------------
                SqlCommand command;
          command = new SqlCommand("use master", connect);
            command.ExecuteNonQuery();
                command = new SqlCommand(@"restore database dbWiseCodes01 from disk = 'c:\SQLBackup\wcBackUp1.bak'", connect);
                command.ExecuteNonQuery();
                //--------------------------------------------------------------------------------------------------------
                connect.Close();

                MessageBox.Show("Has been restored database", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        else
            MessageBox.Show(@"Do not make any endorsement above (or is not in the correct path)", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }

}

Print PDF with JPedal

Sunday, August 16th, 2009

Researching a bit about the handling of a PDF document I found a library called JPedal for manipulating PDF documents from Java.
Like other libraries I’ve seen among other iText and iReport, which are very comprehensive and allow you to do many tasks, including printing. Disadvantage that the latter is that you need to have installed Acrobat Reader and for many users this is not possible.
But even with JPedal lets you see the Acrobat Reader tools within the Java application, providing a task pane for the PDF to manipulate.

With PrinterJob.lookupPrintServices can get the services available and print them PrinterJob a concrete one.

PrintService[] psService = PrinterJob.lookupPrintServices();
PrinterJob pjPrintJob = PrinterJob.getPrinterJob();
pjPrintJob.setPrintService(psService[0]);

// Assigns the size of the paper to A4.

Paper paper = new Paper();
paper.setSize(595, 842);
paper.setImageableArea(0, 0, 595, 842);
PageFormat pf = pjPrintJob.defaultPage();
pf.setPaper(paper);

Loads the PDF to be printed. The file is called wc_PDF.pdf printed and given format.

PdfDecoder pdfD = null;
pdfD = new PdfDecoder(true);
pdfD.openPdfFile("wc_PDF.pdf");
pdfD.setPageFormat(pf);

It sends the file to print

printJob.setPageable(pdfD);
printJob.print();

And to finalize the document is closed.

pdf.closePdfFile();

Download JPedal..

The example would then complete as follows:

import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import javax.print.PrintService;
import org.jpedal.PdfDecoder;

public final void wc_PrintPDF() {
    PdfDecoder pdfD = null;
    try {
        PrintService[] psService = PrinterJob.lookupPrintServices();
        PrinterJob pjPrintJob = PrinterJob.getPrinterJob();
        pjPrintJob.setPrintService(psService[0]);

        Paper paper = new Paper();
        paper.setSize(595, 842);
        paper.setImageableArea(0, 0, 595, 842);
        PageFormat pf = pjPrintJob.defaultPage();
        pf.setPaper(paper);

        pdfD = new PdfDecoder(true);
        pdfD.openPdfFile("wc_PDF.pdf");
        pdfD.setPageFormat(pf);

        pjPrintJob.setPageable(pdfD);
        pjPrintJob.print();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        pdfD.closePdfFile();
    }
}

ASP: Online Users Counter

Monday, August 10th, 2009

This popular script is found in almost all sites in ASP, used to count visitors assets (present at the time), is on our website.

The code should be used in the file Global.asa. Must not be enclosed in <% and%> must be unique and that has within it. (Well, not unique, but playing with Global.asa not recommend it).

Here’s the code that goes into the Global.asa

<script language=vbscript runat=server> 

Sub Application_OnStart
Application("Active") = 0
End Sub 

Sub Application_OnEnd
End Sub 

Sub Session_OnStart
Application.Lock
Application("Active") = Application("Active") + 1
Application.Unlock
End Sub 

Sub Session_OnEnd
Application.Lock
Application("Active") = Application("Active") - 1
Application.Unlock
End Sub 

</script>

And to show the information which the Global.asa, or to show active users as I did in my example, they should put the following on the page displaying the data:

<P>There are currently <%=Application("Active")%> user's on our site</P>

Happy Programming!!! ;)

Javascript: Tic Tac Toe

Monday, August 10th, 2009

live_preview View Demo downloadDownload Code [3.29 kb]

Playing

The computer always plays with circles ( “O”) and you with blades
( “X”). Start your. To put an X have to click on the button
the bottom panel that corresponds to the position you want to put it. You can
also hand-write it, always with capital letters (without cheating, because the
computer trusts you).

The computer will make its redondel every time you put your X .
Never make a mistake, and if you neglect (and you do not cheat), you win. If you cheat, do not
work correctly.

When the game ends, the computer shows the result and increase the counters
lower. To play another game, press the button again Game , which
Clean the panel game. To clear the counters, click the Clear button Clear.

This < head> between and </head>:

<script language="javascript" type="text/javascript">
// Tic Tac Toe
// Version: 1 (10/08/2009)
// Venu Thomas
// This script and many others can
// download online for free
// in the code: [url = http://www.wisecodes.com] www.wisecodes.com [/ url] 

// To understand the explanations:
// Win - and win puts
// Game - and has put in a two-line 'O' and an empty box
// Defend - keep winning the next move in the opposite
// It makes no sense at first occupy the center if there is victory or play
// There must defend first and attack later. First look for the victory, then
// search and then defends move 

// global variable
var strPlaying = true   

//ROLE PLAY CHECK------------------------------------------------
function wc_fnCheckPlay(grid, record) {
    // check that it is possible to stripe 3 in a row, column or diagonal
     // returns the position where you have to put the record to do so and -1 if there is no gamble   

    var x, y   

    for(x = 0; x < 9; x += 3) {      //Check the rows
        if ((grid.elements[x].value == record) && (grid.elements[x + 1].value == record))
            if (grid.elements[x + 2].value == "")
                return (x + 2)
        if ((grid.elements[x].value == record) && (grid.elements[x + 2].value == record))
            if (grid.elements[x + 1].value == "")
                return (x + 1)
        if ((grid.elements[x + 1].value == record) && (grid.elements[x + 2].value == record))
            if (grid.elements[x].value == "")
                return (x)
    }   

    for(x = 0; x < 3; x++) {     //Check the columns
        if ((grid.elements[x].value == record) && (grid.elements[x + 3].value == record))
            if (grid.elements[x + 6].value == "")
                return (x + 6)
        if ((grid.elements[x].value == record) && (grid.elements[x + 6].value == record))
            if (grid.elements[x + 3].value == "")
                return (x + 3)
        if ((grid.elements[x + 3].value == record) && (grid.elements[x + 6].value == record))
            if (grid.elements[x].value == "")
                return (x)
    }   

    //check the diagonals
    if ((grid.elements[2].value == record) && (grid.elements[4].value == record) && (grid.elements[6].value == ""))
        return (6)
    if ((grid.elements[2].value == record) && (grid.elements[4].value == "") && (grid.elements[6].value == record))
        return (4)
    if ((grid.elements[2].value == "") && (grid.elements[4].value == record) && (grid.elements[6].value == record))
        return (2)
    if ((grid.elements[0].value == record) && (grid.elements[4].value == record) && (grid.elements[8].value == ""))
        return (8)
    if ((grid.elements[0].value == record) && (grid.elements[4].value == "") && (grid.elements[8].value == record))
        return (4)
    if ((grid.elements[0].value == "") && (grid.elements[4].value == record) && (grid.elements[8].value == record))
        return (0)   

    return -1
}   

//HORIZONTAL PARTNER ROLE
function wc_fnPartnerHorizontal(grid, record) {
    // check if it's possible to put 2 in a row, the other empty position ...
     //... same row
     // returns the row to do so, or -1 if not 

    var x, y   

    for(x = 0; x < 9; x += 3) {      //Check the rows
        if ((grid.elements[x].value == record) && (grid.elements[x + 1].value == "") && (grid.elements[x + 2].value == ""))
            return (x)
        if ((grid.elements[x].value == "") && (grid.elements[x + 1].value == record) && (grid.elements[x + 2].value == ""))
            return (x + 1)
        if ((grid.elements[x].value == "") && (grid.elements[x + 1].value == "") && (grid.elements[x + 2].value == record))
            return (x + 2)
    }   

    return -1
}   

//VERTICAL PARTNER ROLE---------------------------------------------------
function wc_fnPartnerVertical(grid, record, playHtal) {
 // check if it's possible to put 2 in a column, the other empty position ...
     //... same column and taking into account whether that position is horizontal pair
     // returns the column if you do not allow horizontal pair, or -1 if not      

    var x, y   

    for(x = 0; x < 3; x++) {         //check the columns
        if ((grid.elements[x].value == record) && (grid.elements[x + 3].value == "") && (grid.elements[x + 6].value == ""))
            if (x != playHtal)        //if partner not interested in horizontal and vertical
                return (x)
        if ((grid.elements[x].value == "") && (grid.elements[x + 3].value == record) && (grid.elements[x + 6].value == ""))
            if ((x + 3) != playHtal)
                return (x + 3)
        if ((grid.elements[x].value == "") && (grid.elements[x + 3].value == "") && (grid.elements[x + 6].value == record))
            if ((x + 6) != playHtal)
                return (x + 6)
    }   

    return -1
}   

//Get POSITION\
function wc_fnGetPosition(playHtal, playVcal) {
 // Find the position that allows you move vertically and horizontally at the same time move
     // known row and column where couples can be

    var x, y, fila, columna
    var position = 0
    matrix = new Array(3)   

    for (x = 0; x < 3; x++) {        //creates a matrix that assigns a row and column position
        matrix[x] = new Array(3)
        for (y = 0; y < 3; y++) {
            matrix[x][y] = position
            position ++
        }
    }   

    for (x = 0; x < 3; x++) {                    //looking for the row and column
        for (y = 0; y < 3; y++) {
            if (matrix[x][y] == playHtal) //find the row
                fila = x
            if (matrix[x][y] == playVcal) //I found the column
                columna = y
        }
    }   

    return (matrix[fila][columna])          //move back position
}   

//FUNCION REDONDELA PUT-------------------------------------------------
function wc_fnPutRedondela(grid) {
    //the ordanador plays

    var play, playHtal, playVcal   

    //attacks and wins
    play = wc_fnCheckPlay(grid, "O")
    if (play != -1) {
        grid.elements[play].value = "O"
        alert('I won!!!')
        document.scoreboard.missing.value++
        strPlaying = false
        return 1
    }   

    //advocates avoiding the rival wins
    play = wc_fnCheckPlay(grid, "X")
    if (play != -1) {
        grid.elements[play].value = "O"
        return 1
    }   

    //attacks and win the next
    playHtal = wc_fnPartnerHorizontal(grid, "O")
    playVcal = wc_fnPartnerVertical(grid, "O", playHtal)
    if ((playHtal != -1) && (playVcal != -1)) {     //you can put 2 and 2 in a row in column
        if ((playHtal != 4) || (playVcal != 4)) {       //is not the center
            play = wc_fnGetPosition(playHtal, playVcal)  //gets where it should put
            grid.elements[play].value = "O"
            return 1
        }
    }   

    //attacks and put two in a row
    if ((playHtal != -1) && (playVcal == -1)) {
        if ((playHtal != 2) && (playHtal != 5) && (playHtal != 8))    //this is arbitrary
            grid.elements[playHtal + 1].value = "O"                        //puts the right
        else
            grid.elements[playHtal - 1].value = "O"                        //placed to the left
        return 1
    }   

    //attacks and put in two column
    if ((playHtal == -1) && (playVcal != -1)) {
        if ((playVcal != 6) && (playVcal != 7) && (playVcal != 8))
            grid.elements[playVcal + 3].value = "O"        //put down
        else
            grid.elements[playVcal - 3].value = "O"        //puts up
        return 1
    }   

    //occupies the center
    if (grid.elements[4].value == "") {
        grid.elements[4].value = "O"
        return 1
    }   

    //This took the first free
    for (x = 0; x < 9; x++)
        if (grid.elements[x].value == "") {
            grid.elements[x].value = "O"
            return 1
        }   

    alert('Draw...')
    document.scoreboard.draw.value++
    strPlaying = false
    return -1
}   

//FUNCION PUT ASPA
function wc_fnPutAspa(grid, position) {   

    //first check that this strPlaying
    if (strPlaying) {
        if (grid.elements[position].value != "")     //empty box
            alert('That box is already occupied.')
        else {                                                  //empty box, you can put
            grid.elements[position].value = "X"  

            //Check if you have won
            if ( wc_fnNotesVictoria(grid, "X") ) {
                alert('Congratulations! You win... :D ')
                document.scoreboard.won.value++
                strPlaying = false
            } else
                wc_fnPutRedondela(grid)
        }
    } else {
        alert('To start a new line \nClick Play again.')
    }
}   

//VICTORIA FUNCTION CHECK
function wc_fnNotesVictoria(grid, record) {   

    //Check if you have earned the record player that plays with  

    var x   

    for(x = 0; x < 9; x += 3) {  //Check the rows
        if ((grid.elements[x].value == record) && (grid.elements[x + 1].value == record) && (grid.elements[x + 2].value == record))
            return true
    }   

    for(x = 0; x < 3; x++) {     //check the columns
        if ((grid.elements[x].value == record) && (grid.elements[x + 3].value == record) && (grid.elements[x + 6].value == record))
            return true
    }   

    //check the diagonals
    if ((grid.elements[2].value == record) && (grid.elements[4].value == record) && (grid.elements[6].value == record))
        return true
    if ((grid.elements[0].value == record) && (grid.elements[4].value == record) && (grid.elements[8].value == record))
        return true   

    return false
}   

</script>

And this from <body> and </body> :

<!-- To display the grid, and Accountants -->
<form name="grid">
  <div align="center"><center>
  <table border="0" width="62%" cellpadding="5">
    <tr>
      <td width="20%"><input type="text" name="T0" size="3"></td>
      <td width="20%"><input type="text" name="T1" size="3"></td>
      <td width="20%"><input type="text" name="T2" size="3"></td>
      <td width="85%" align="right"></td>
    </tr>
    <tr>
      <td width="20%"><input type="text" name="T3" size="3"></td>
      <td width="20%"><input type="text" name="T4" size="3"></td>
      <td width="20%"><input type="text" name="T5" size="3"></td>
      <td width="85%" align="right"></td>
    </tr>
    <tr>
      <td width="20%"><input type="text" name="T6" size="3"></td>
      <td width="20%"><input type="text" name="T7" size="3"></td>
      <td width="20%"><input type="text" name="T8" size="3"></td>
      <td width="85%" align="right"></td>
    </tr>
    <tr>
      <td width="20%"><input type="button" value=" X " name="B0" onClick="wc_fnPutAspa(grid, 0)" class="metal"></td>
      <td width="20%"><input type="button" value=" X " name="B1" onClick="wc_fnPutAspa(grid, 1)" class="metal"></td>
      <td width="20%"><input type="button" value=" X " name="B2" onClick="wc_fnPutAspa(grid, 2)" class="metal"></td>
      <td width="85%"><input type="reset" value="New game" name="new" onClick="strPlaying=true" class="metal"></td>
    </tr>
    <tr>
      <td width="18%"><input type="button" value=" X " name="B3" onClick="wc_fnPutAspa(grid, 3)" class="metal"></td>
      <td width="17%"><input type="button" value=" X " name="B4" onClick="wc_fnPutAspa(grid, 4)" class="metal"></td>
      <td width="18%"><input type="button" value=" X " name="B5" onClick="wc_fnPutAspa(grid, 5)" class="metal"></td>
      <td width="85%"></td>
    </tr>
    <tr>
      <td width="18%"><input type="button" value=" X " name="B6" onClick="wc_fnPutAspa(grid, 6)" class="metal"></td>
      <td width="17%"><input type="button" value=" X " name="B7" onClick="wc_fnPutAspa(grid, 7)" class="metal"></td>
      <td width="18%"><input type="button" value=" X " name="B8" onClick="wc_fnPutAspa(grid, 8)" class="metal"></td>
      <td width="85%" align="right"></td>
    </tr>
  </table>
  </center></div>
</form>

<form name="scoreboard">
  <div align="center"><center>
  <table border="0" width="62%" cellpadding="5" cellspacing="0">
    <tr>
      <td width="20%"><small>draw:<br>
      </small><input type="text" name="draw" value="0" size="6"></td>
      <td width="20%"><small>missing:<br>
      </small><input type="text" name="missing" value="0" size="6"></td>
      <td width="20%"><small>won:<br>
      </small><input type="text" name="won" value="0" size="6"></td>
      <td width="85%"> <br><input type="reset" value="Clear" name="delete" class="metal"></td>
    </tr>
  </table>
  </center></div>
</form>

<h2>Playing</h2>
<p>The computer always plays with <em> circles </em> ( "O") and you with <em> blades </em>
( "X"). Start your. To put an X <em> </em> have to click on the button
the bottom panel that corresponds to the position you want to put it. You can
also hand-write it, always with capital letters (without cheating, because the
computer trusts you).</p>
<p>The computer will make its <em> redondel </em> every time you put your <em> X </em>.
Never make a mistake, and if you neglect (and you do not cheat), you win. If you cheat, do not
work correctly.</p>
<p>When the game ends, the computer shows the result and increase the counters
lower. To play another game, press the button again <strong> Game </strong>, which
Clean the panel game. To clear the counters, click the Clear button <strong>Clear</strong>.</p>

Happy Programming!!! ;)

Multiline in JavaScript

Thursday, August 6th, 2009

Whenever you try to write a script in Javascript that requires a string of multiple lines get an error code that is poorly trained. That is a problem for these scripts to generate HTML content, because by having a clear line and we lose we do not see exactly what you’re painting.

$('#ID').append(
   '<div id="wcDIV"> \
      <p>Welcome to WiseCodes.Com!</p> \
    </div>'
);

var strWelcome = 'Welcome \
to WiseCodes.Com!'

The key is used (\) to indicate the line, that mysteriously causes the browser detects that it is a single line, making the job of uniting us.
A curiosity of this language that helps us to make things easier and above all clear.

Happy Programming !!! ;-)

The best way to load javascript

Tuesday, August 4th, 2009

Nicholas C. Zakas has been thinking about the issue and has taken 3 points needed to be taken to improve the load javascript on our pages.

* Create two files Javascript. In the first place you need to dynamically load another javascript file and the second with the code needed for our application.
* Javascript includes the first end of the page just above < / body >
* Just below we create a second tag < script > where to call / the file / s needed.

Our HTML would be more or less like this:

<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>

loadScript ()

loadScript () function is responsible for loading the Javascript file in a dynamic and responsible for implementing the code as the second parameter to indicate when it is loaded correctly.

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);
}

Clearly, these optimizations improve outcome, although we are talking about milliseconds (or seconds in the worst case). But it’s good to know how to improve our scripts and pulirlos well.

Happy Programming!!! ;)

Doodle.js, library for working with canvas

Friday, July 3rd, 2009

Doodle.js is a library that allows us to easily work with the element <canvas /> and everything that entails. With a similar aesthetic to jQuery, drawing on the canvas that is <canvas /> is as simple as this:


  <head>
  <!--[if IE]><script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script><![endif]-->
  <script src="./doodle-0.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    function init() {
      (function(oo) {
  oo.canvas('#my_canvas');
  oo.rect({x:25, y:25, width:50, height:50}).draw();

})($doodle);

    };
  </script>
  </head>
  <!--init() is called when the canvas is ready for us.-->
  <body onload="javascript:init();">
    <canvas id="my_canvas" width="600" height="400">
      <p>Fallback: Canvas element is not supported in this browser!</p>
    </canvas>
  </body>

Examples

Do not miss some of the examples available on the homepage of the library:
Spiral multicolor
Rebounds multiple

Proposal subtitle for HTML5 video tag

Friday, July 3rd, 2009

In Ginger’s Thoughts I read a very interesting proposal which I believe is that in just a proposal. Although the idea is very good and it might be interesting to have this in the new HTML5. The proposal is for December 2008 and so far no developments.
The idea is to include the tag HTML5′s ability to handle subtitles:

<video src="http://example.com/video.ogv" controls>
<text category="CC" lang="en" type="text/x-srt" src="caption.srt"></text>
<text category="SUB" lang="de" type="application/ttaf+xml" src="german.dfxp"></text>
<text category="SUB" lang="jp" type="application/smil" src="japanese.smil"></text>
<text category="SUB" lang="fr" type="text/x-srt" src="translation_webservice/fr/caption.srt"></text>
</video>

As we can see in the above code, we would be including the text tag that would allow us to establish the lang attribute of the subtitle language and select it from your control in your browser (the preset default language of your browser) .

The tag <text />
Only indicate the location of the subtitle file to load src indicating the language lang and type type of a subtitle that we carry.

For now …
At the moment we can make use of SRT jQuert to simulate the result with Javascript.

<!-- Javascript -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.srt.js"></script>

<!-- HTML  -->
<video src="http://example.com/video.ogv" id="video" controls>
<div class="srt"
data-video="video"
data-srt="http://example.com/video.srt" />

The idea is interesting when the films arrive officially to the Internet. Huh?