Archive for August, 2009

Google Code Jam returns

Wednesday, August 12th, 2009

GoogleCodeJam

Energizes you find the solution to a difficult problem? You want to write code? Here at Google, we know that produces pleasure to find a challenge, confront and transform the solution into a code. Since 2003, we have been sharing this experience with the global community of programmers through our annual competition, Google Code Jam. Today we are proud to announce Google Code Jam 2009, powered by Google App Engine.

This year, participants will compete in several rounds of 2 1/2 hours online in what must solve three or four difficult algorithmic problems in each wheel. To write source solutions, will use the programming languages and tools they prefer, when the solutions are compared with ours. A single mistake from hundreds of solutions, and re-start again.

The entries begin today. So visit the site of the Google Code Jam to sign up, read the rules, and more importantly – a practice started by reviewing the issues raised last year to help you when you’re ready to begin the qualifying rounds of September 2. After four tough rounds of competition online, the top 25 competitors will be invited to our headquarters in Mountain View to determine the award of $ 5000 U.S. dollars and the title of champion of our Google Code Jam.

Link: via Google Code Jam 2009

Starting with Java and MySQL

Wednesday, August 12th, 2009

MySQL database is a very popular and highly recommended for web programming and for programming. Despite being free, is very stable and very practical to work with different applications. In this case, the idea is to make a very basic example working for a SELECT query the database MySQL Java yourself.

Java allows a connection to MySQL calls with a few simple lines. To create the connection between the database and we will need the java conectot that offers mysql, can be downloaded here. Assuming you already have your connection in the library caperta your java project, and then installed MySLQ started to work.

1. Establishing the connection
2. Select Query
3. Extract information ResulSet
4. Other Select

Establishing the connection

When you install mysql, during installation we have compiled a series of data that are of utmost importance. talking about the username and password for the database, besides that, we must also have the name of the database with which we work. In summary we need:

  1. User
  2. Password
  3. name of the database
  4. host (if the database is in our pc then the hostname is localhost)
  5. port (if mysql is installed in the conventional way then the port number 3306 unless you have changed manually)

Whether we make the connection in a separate class the main one, the connection is created in the same way as follows:

Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/wc_data_base", "user", "password"); 

If you notice, the getConnection method that takes a String containing the data mentioned above and turn it into a valid URL to create the connection. If all goes well then you only have to prepare and execute the query.

Select Query

Let’s start with creating a method called wc_select_query is going to have to create a select statement to the database. It is the part where we enter the most serious, and there are certain aspects to be clear before you run SQL commands from java. Assuming you already have basic knowledge in SQL query to differentiate when a query only extracts information or if a query modifies the database, depending on these rules we will use two different methods, to better illustrate:

  • SELECT: Use the executeQuery method in java to run the query, because it does not alter the database, only extracts information
  • INSERT, UPDATE and DELETE: Use executeUpdate method in java to run the query, because these consultations if altered information in the database.

By now a little confusing, but henceforth will be more clear. Before continuing let’s assume that our database has the tables countries and person who have the information that we are going to work.

person table

person_id name surename age country
1 venu thomas venu thomas 26 1
2 veena thomas veena thomas 18 1
3 wounder vander heji wounder 28 4
4 danny thomas castro 25 3
5 andera the tower 34 2
6 roy rog 27 3
7 henry philip 35 3
8 daniel daniel 29 5
9 rodriguez nakul 19 2

country table:

country_id name size
1 India big
2 United States big
3 UK small
4 Germany small

The tables are very basic, just a detail, note that there is a foreign key from the table Person (country) to the country table (country_id).

So, our method is to wc_select_query order to generate the query “select all persons are called danny thomas.” Prepare the query:

Statement query = (Statement) c.createStatement();
ResultSet resultado = query.executeQuery("select * from person where name = 'danny thomas'");

C with the object that created the Statement object that will be responsible for executing the query, inside the SQL statement. The result of this query stored in an object of type ResulSet, this object behaves like a virtual table that contains the information out of the ruling of the select, ie the value of result is:

4 danny thomas castro 25 3

To make an overview of how the method was wc_select_query have something like this:

public void wc_select_query() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_data_base", "user", "password");
Statement query = (Statement) c.createStatement();
ResultSet result = query.executeQuery("select * from person where name = 'danny thomas'");

} catch (SQLException ex) {
System.out.println("There was an error with the SQL commands");
} catch (ClassNotFoundException ex2){
System.out.println("Could not load the driver");
}
}

Extracting information ResulSet

Using the above method and now only need to extract the information stored outcome variable. This variable is the name of each column as the result showed that the query also has a number of rows in each record. Then, we proceed to extract the data:

int column_person_id = result.findColumn("person_id");
int column_name = result.findColumn("name");
int column_age = result.findColumn("age");
int column_country = result.findColumn("country");

boolean full = result.next();

while (full){
int id = result.getInt(column_student_id);
String name = result.getString(column_name);
int age = result.getInt(column_age);
int country = result.getInt(column_country);
full = result.next();

System.out.println("id: " + id + "n" +
"name: " + name + "n" +
"age: " + age + "n"+
"country: " + country);
}

The code above is very different methods, their functionality depends on the type of information contained in each column.

  • findColumn (column_name): search the index of the column. By knowing the index of the column know that we can extract data accurately. For example, column 1 is the column person_id, which we already know that this column will only have numeric data types. Similarly for column 2, which is responsible for having the names of people, in other words, data String
  • next (): This method tells us if the result (ResulSet) is empty or not, ie, it returns false. If it is empty is because the SELECT query did not generate any results, because no records meet all conditions. On the other hand, has returned true record, the variables used by iterating the cycle to go between each record
  • getInt (column_index), GetString (column_index): These methods, and extract information from the result, depending on the type of data that will be the specific method call. For the example of the Person table only has two types of data, numeric and string, but the API ResulSet gives us if we use other methods such as double data types, date, long, etc.

Finally, it would be complete method …

public void wc_select_query() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_data_base", "user", "password");
Statement query = (Statement) c.createStatement();
ResultSet result = query.executeQuery("select * from person where name = 'danny thomas'");

int column_person_id = result.findColumn("person_id");
int column_name = result.findColumn("name");
int column_age = result.findColumn("age");
int column_country = result.findColumn("country");

boolean full = result.next();

while (full){
int id = result.getInt(column_student_id);
String name = result.getString(column_name);
int age = result.getInt(column_age);
int country = result.getInt(column_country);
full = result.next();

System.out.println("id: " + id + "n" +
"name: " + name + "n" +
"age: " + age + "n"+
"country: " + country);
}

} catch (SQLException ex) {
System.out.println("There was an error with the SQL commands");
} catch (ClassNotFoundException ex2){
System.out.println("Could not load the driver");
}
}

The output sample would be:

id: 4
Name: danny thomas
Age: 25
country: 3

Another way to make the shortest method is to remove the indexes of the columns, and metods GetString and getInt is pass the name or the index of the column directly, such as:

//like this:
String name = result.getString("name");

//or like this:
int edad = result.getInt(4);

Other Select

Sometimes when we work with several tables, most often avoids a relationship between them, this natural relationship is through foreign keys (as recommended), ie in order to have a better design of the database .
Using the previous example of the tables of people and countries we can see that their relationship is over and the country country_id respectively. So supogamos we all want the names of people and the country to which they belong. Here the trap is that the column name of Pserson and the column name the countries are called equal, then we as specified everything …

name name
venu thomas India
veena thomas India
wounder vander heji Germany
danny thomas UK
andera United States
roy UK
henry UK
daniel India
rodriguez United States

Now, here is a conflict of names of columns, how to differentiate ResulSet not refer to any column by name when you speak of columns with two columns has the same name, ie name. In this case we must get the column data by column number. The count of columns in the ResulSet starts from 1 not from 0 as is usuarial, then, to refer to names of persons and names of countries would be …

String name_person = result.getString(1); // 1 = first column
String name_country = result.getString(2); // 2 = second column

Happy Programming!!! ;)

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

My new Blog for Apple fans!

Monday, August 10th, 2009

Check out this link Apple.WiseCodes.Com! As you’ve guessed this blog you’ll find everything about the universe of products and services Apple Mac OS, iPod, laptops, desktops …. but also the buzz, the most useful tips and detailed information about the company. Careful, if you’re not yet a user of Apple, this blog might make you change your mind.

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

Optical illusion: Horse that is driven by CSS

Saturday, August 8th, 2009

OpticaIllusionParallaxCss_080809

Have you heard of the magic book Magic Moving Images ?? (Video: see below) With CSS, and Parallax can create an optical illusion similar to that which appears the silhouette of a horse moves horizontally to resize the window in our browser. Although the sample is not perfectly equal to the original book, it seems a lot.
You can download the source code hack directly or by example (resize the window horizontally to move the horse):

View Demo

If you want to learn how to create your own optical illusion similar to the horse, follow these steps.

10 javascript frameworks that need to know

Thursday, August 6th, 2009

Web developers, designers and typesetters should already know JavaScript. The javascript does not know should Wearing batteries to keep the language client for the future (and present).
For those who defend us a little on the subject and we extend our capacity and speed of development can opt to use a framework to give us a lot of options for everyday use.

* SproutCore
* Spry
* JavaScriptMVC
* qooxdoo
* Midori
* Archetype JavaScript Framework
* June Framework
* UIZE
* SimpleJS
* Fleegix.js

XHTML Validation

Thursday, August 6th, 2009

Well, after 2 days of fighting, I was able to validate the code for the blog and the RSS, I have left the CSS, because the truth is that while I’ve been planning just got bad habits that result in problems of validation.

Why is it so important?

Truly validate a web only thing it gives you an icon you can see below, since it works exactly like the website and may even be incompatible with some versions of browsers or earlier versions of the most popular.
It is a way to standardize your work to achieve in the future to follow a standard and that the websites are governed by it. Making life easier for Web developers, who are now scrambling to get webs with 3 or more browsers …
In addition to thus facilitate the indexing of search engines dealing with code like XML, to be well formed indexing is more optimistic.

What earned my site?

Well the first thing you need is free time and good luck :D
Since the W3C URL can get down to work, following the steps gives us to solve the “validation errors”.
For Web feeds would be this.

WordPress + Validation

One thing to remember is that WordPress makes creating news in our HTML code and you do not really all that well, and the publisher have not provided us with rich work, getting malformed tags (not always).

usability, programming, XHTML, standard, validacion

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