Programmering · Webbutveckling
JavaScript
Modern JavaScript, jQuery och praktiska kodmönster
01 · Översikt
Vad du hittar här
Kodexempel i JavaScript: grundläggande funktioner, jQuery och moderna ES6+-mönster, plus några riktlinjer för kvalitet och prestanda i webbutveckling.
3
Core-exempel
3
jQuery-exempel
3
ES6+-mönster
4
Best practices
02 · Grunderna
Core JavaScript
Reload Current Page
Programmatically reload the current page using JavaScript.
window.location.assign(window.location.href);Generate Random GUID
Generate a universally unique identifier (UUID/GUID) in JavaScript.
function NewGuid() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
// Usage
const newId = NewGuid();
console.log(newId); // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"Date Formatting Extension
Extend Date prototype to format dates as YYYY-MM format.
Date.prototype.yyyymm = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]); // padding
};
// Usage
const date = new Date();
console.log(date.yyyymm()); // "2024-03"03 · jQuery
jQuery
jQuery UI Datepicker Configuration
Configure jQuery UI datepicker with custom date format and controls.
$('.js-datepicker').datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true,
showButtonPanel: true,
closeText: "Close",
currentText: "Today"
});AJAX Form Submission
Submit form data using jQuery AJAX with error handling.
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: 'POST',
data: $(this).serialize(),
success: function(response) {
console.log('Success:', response);
// Handle success
},
error: function(xhr, status, error) {
console.error('Error:', error);
// Handle error
}
});
});Dynamic Content Loading
Load content dynamically and handle loading states.
function loadContent(url, targetElement) {
$(targetElement).html('<div className="loading">Loading...</div>');
$.get(url)
.done(function(data) {
$(targetElement).html(data);
})
.fail(function() {
$(targetElement).html('<div className="error">Failed to load content</div>');
});
}
// Usage
loadContent('/api/content', '#content-container');04 · ES6+
Modern JavaScript
ES6+ Arrow Functions
Modern arrow function syntax and usage patterns.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Array methods with arrow functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);Async/Await Pattern
Modern asynchronous JavaScript using async/await.
// Fetch data with async/await
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const userData = await response.json();
return userData;
} catch (error) {
console.error('Error fetching user data:', error);
throw error;
}
}
// Usage
const userData = await fetchUserData(123);Destructuring and Spread
Modern JavaScript destructuring and spread operator patterns.
// Object destructuring
const user = { name: 'John', age: 30, email: 'john@example.com' };
const { name, age, ...rest } = user;
// Array destructuring
const [first, second, ...others] = [1, 2, 3, 4, 5];
// Spread operator
const newUser = { ...user, age: 31 };
const newArray = [...numbers, 6, 7, 8];
// Function parameter destructuring
function updateUser({ id, name, email }) {
// Update user with provided fields
}05 · Kvalitet
Best practices
- Use Strict ModeAlways use 'use strict' to catch common coding mistakesExempel: Add 'use strict'; at the top of JavaScript files
- Avoid Global VariablesMinimize global scope pollution by using modules or namespacesExempel: Use IIFE patterns or modern ES6 modules
- Handle Errors GracefullyAlways include error handling for asynchronous operationsExempel: Use try/catch with async/await or .catch() with Promises
- Use Semantic Variable NamesChoose descriptive names that explain the variable's purposeExempel: Use 'userEmail' instead of 'ue' or 'data'
06 · Prestanda
Performance
- DOM ManipulationMinimize direct DOM access and batch DOM updatesLösning: Use document fragments or virtual DOM libraries for complex updates
- Event DelegationUse event delegation instead of attaching listeners to many elementsLösning: Attach one listener to parent element and use event.target
- Debounce User InputPrevent excessive function calls on user input eventsLösning: Use debouncing for search inputs, resize handlers, etc.
- Lazy LoadingLoad content only when needed to improve initial page loadLösning: Use Intersection Observer API for images and content
07 · Tips
Utvecklingstips
- Använd utvecklarverktygen
- Lär dig webbläsarens utvecklarverktyg för debugging och performance-analys.
- Testa kod regelbundet
- Skriv och kör tester för dina funktioner med Jest eller liknande ramverk.
- Håll dig uppdaterad
- JavaScript utvecklas snabbt, följ MDN Web Docs och moderna best practices.