Perchè caricare sempre tutto il nostro codice javascript al caricamento della pagina?
In questo modo si appesantisce la pagina stessa senza che probabilmente un certo codice non venga neppure usato
JQuery rende semplice caricare ed far eseguire un file javascript tanto quanto lo è stato caricare una pagina html con un semplice metodo: getScript('')
Per la lettera C del nostro dizionario caricheremo un file javascript dove avrò definito una variabile contenente l'array delle mie informazioni e la logica di parsing e costruzione html:
Javascript code:
var entries = [
{
"term": "CALAMITY",
"part": "n.",
"definition": "A more than commonly plain and unmistakable
reminder that the affairs of this life are not of
our own ordering. Calamities are of two kinds:
misfortune to ourselves, and good fortune to
others."
},
{
"term": "CANNIBAL",
"part": "n.",
"definition": "A gastronome of the old school who preserves the
simple tastes and adheres to the natural diet of
the pre-pork period."
},
{
"term": "CHILDHOOD",
"part": "n.",
"definition": "The period of human life intermediate between the
idiocy of infancy and the folly of youth —
two removes from the sin of manhood and three from
the remorse of age."
}
];
var html = '';
$.each(entries, function() {
html += '<div class="entry">';
html += '<h3 class="term">' + this['term'] + '</h3>';
html += '<div class="part">' + this['part'] + '</div>';
html += '<div class="definition">' + this['definition'] + '</div>';
html += '</div>';
});
$('#dictionary').html(html);
Dopo aver definito questo la logica in questo file, vado a caricarlo all'interno della mia pagina:
Javascript code:
$(document).ready(function() {
$('#letter-c .button').click(function() {
$.getScript('c.js');
});
});