Web Systems and Technologies: Chương 04 - Tìm Hiểu Về JavaScript

Khám phá các hệ thống và công nghệ web với JavaScript trong bài viết này. Nâng cao kỹ năng lập trình và hiểu biết về phát triển web.

Người đăng

Ẩn danh
67
3
0

Phí lưu trữ

30 Point

Mục lục chi tiết

4. CHƯƠNG 4: Java Script Content

4.1. What is JavaScript

4.2. The Foundation of JavaScript Syntax

4.3. The Core language Objects in JavaScript

4.4. Document Object Model (DOM) and The Browser Objects in JavaScript

Tóm tắt

I. Tổng Quan Về JavaScript Trong Hệ Thống Web

JavaScript là một ngôn ngữ lập trình kịch bản mạnh mẽ, được sử dụng rộng rãi trong phát triển web. Ngôn ngữ này cho phép tạo ra các trang web động và tương tác, giúp cải thiện trải nghiệm người dùng. JavaScript có thể chạy trên cả phía máy khách và máy chủ, mang lại sự linh hoạt cho các nhà phát triển. Được phát triển bởi Sun Microsystems và Netscape, JavaScript đã trở thành một phần không thể thiếu trong các ứng dụng web hiện đại.

1.1. JavaScript Cơ Bản Định Nghĩa và Lịch Sử

JavaScript được phát triển từ Livescript của Netscape. Ngôn ngữ này cho phép lập trình viên tạo ra các ứng dụng web tương tác, từ việc xử lý sự kiện đến việc thay đổi nội dung trang mà không cần tải lại. Sự phát triển của JavaScript đã mở ra nhiều cơ hội cho các nhà phát triển web.

1.2. Tại Sao JavaScript Quan Trọng Trong Phát Triển Web

JavaScript cho phép tạo ra các trang web động, giúp người dùng tương tác một cách mượt mà. Nó hỗ trợ nhiều tính năng như xác thực biểu mẫu, xử lý sự kiện và thay đổi nội dung trang. Điều này làm cho JavaScript trở thành một công cụ không thể thiếu trong phát triển web hiện đại.

II. Những Thách Thức Khi Sử Dụng JavaScript Trong Phát Triển Web

Mặc dù JavaScript mang lại nhiều lợi ích, nhưng cũng tồn tại một số thách thức. Các vấn đề về bảo mật, hiệu suất và khả năng tương thích giữa các trình duyệt là những điều cần được xem xét. Việc viết mã JavaScript không đúng cách có thể dẫn đến lỗi và trải nghiệm người dùng kém.

2.1. Vấn Đề Bảo Mật Trong JavaScript

JavaScript có thể bị tấn công thông qua các lỗ hổng như XSS (Cross-Site Scripting). Điều này có thể dẫn đến việc kẻ tấn công thực hiện các hành động không mong muốn trên trang web. Do đó, việc bảo vệ mã JavaScript là rất quan trọng.

2.2. Hiệu Suất và Tương Thích Trình Duyệt

JavaScript có thể ảnh hưởng đến hiệu suất của trang web nếu không được tối ưu hóa. Ngoài ra, không phải tất cả các trình duyệt đều hỗ trợ các tính năng mới nhất của JavaScript, điều này có thể gây ra sự không nhất quán trong trải nghiệm người dùng.

III. Phương Pháp Tối Ưu Hóa JavaScript Để Nâng Cao Hiệu Suất

Để tối ưu hóa JavaScript, các nhà phát triển có thể áp dụng nhiều phương pháp khác nhau. Việc sử dụng các công cụ như minification, bundling và lazy loading có thể giúp cải thiện tốc độ tải trang và hiệu suất tổng thể.

3.1. Sử Dụng Minification Để Giảm Kích Thước Tập Tin

Minification là quá trình loại bỏ các ký tự không cần thiết trong mã JavaScript, giúp giảm kích thước tập tin. Điều này giúp tăng tốc độ tải trang và cải thiện hiệu suất.

3.2. Bundling Nhiều Tập Tin JavaScript

Bundling là quá trình kết hợp nhiều tập tin JavaScript thành một tập tin duy nhất. Điều này giúp giảm số lượng yêu cầu HTTP và cải thiện tốc độ tải trang.

IV. Ứng Dụng Thực Tiễn Của JavaScript Trong Phát Triển Web

JavaScript được sử dụng rộng rãi trong nhiều ứng dụng web hiện đại. Từ việc tạo ra các trang web tương tác đến việc phát triển các ứng dụng đơn trang (SPA), JavaScript đã chứng minh được giá trị của mình trong lĩnh vực phát triển web.

4.1. JavaScript Trong Các Ứng Dụng Đơn Trang

Các ứng dụng đơn trang (SPA) sử dụng JavaScript để tải nội dung mà không cần tải lại trang. Điều này giúp cải thiện trải nghiệm người dùng và tăng tốc độ phản hồi của ứng dụng.

4.2. Tích Hợp JavaScript Với HTML và CSS

JavaScript có thể tương tác với HTML và CSS để thay đổi nội dung và kiểu dáng của trang web. Việc này cho phép tạo ra các hiệu ứng động và tương tác phong phú cho người dùng.

V. Kết Luận Tương Lai Của JavaScript Trong Phát Triển Web

JavaScript sẽ tiếp tục đóng vai trò quan trọng trong phát triển web trong tương lai. Với sự phát triển của các công nghệ mới như Node.js và các framework như React, Angular, JavaScript sẽ ngày càng trở nên mạnh mẽ hơn.

5.1. Xu Hướng Mới Trong JavaScript

Các xu hướng mới như lập trình hàm và lập trình bất đồng bộ đang trở thành phổ biến. Điều này giúp cải thiện khả năng mở rộng và hiệu suất của ứng dụng web.

5.2. Tương Lai Của JavaScript Trong Các Ứng Dụng Web

JavaScript sẽ tiếp tục phát triển và thích ứng với các nhu cầu mới trong phát triển web. Sự ra đời của các công nghệ mới sẽ mở ra nhiều cơ hội cho các nhà phát triển.

24/07/2025

Trích đoạn nội dung tài liệu

Web Systems and Technologies Chapter 04. Java Script Content  What is JavaScript  The Foundation of JavaScript Syntax  The Core language Objects in JavaScript  Document Object Model (DOM) and The Browser Objects in JavaScript 2 The Foundation of JavaScript Syntax 3 What is JavaScript  It is a scripting language that can be used to create client-side scripts and server-side scripts.  JavaScript makes it easier to create dynamic and interactive Web pages.  JavaScript is a scripting language developed by Sun Microsystems and Netscape.

 JavaScript developed from Netscapes’s Livescript.  Client applications run in a browser such as Netscape Navigator, Google Chrome, FireFox or Internet Explorer. 4 JavaScript Advantages  JavaScript allows interactivity such as:  Implementing form validation  React to user actions, e. handle keys  Changing an image on moving mouse over it  Sections of a page appearing and disappearing  Content loading and changing dynamically  Performing complex calculations  Custom HTML controls, e.

scrollable table  Implementing AJAX functionality 5 What Can JavaScript Do?  Can handle events  Can read and write HTML elements and modify the DOM tree  Can validate form data  Can access / modify browser cookies  Can detect the user’s browser and OS  Can be used as object-oriented language  Can handle exceptions  Can perform asynchronous server calls (AJAX) 6 Embedding JavaScript in Web Page  The JavaScript can be inserted into an HTML document in the following ways :  Using SCRIPT tag: <script language="JavaScript"> <!-- JavaScript statements; //--> </script>  Using an external File <script language="JavaScript“ src="filename.js"> </script>  Using JavaScript Expressions within HTML Tag Attribute Values  Using JavaScript in event handlers 7 JS Variables  A variable is a container that refers to a memory location.  It is used to hold values that may change while the script is executing.  Variables follow some naming conventions.  A variable is declared using the keyword ‘var’.

var A = 10;  Variables have a scope that is determined by where they are declared in the script.  Global Variable  Local Variable  Literals are fixed values that can be used in the script. 8 JS Variables (1)  String type – string of characters var myName = "You can use both single or double quotes for strings";  Arrays var my_array = [1, 5.3, "aaa"];  Associative arrays (hash tables) var my_hash = {a:2, b:3, c:"text"}; 9 JS Data Types  JavaScript has a relatively small set of data types.  Numbers  Logical or Boolean  Strings  Null  JavaScript is case-sensitive.

 In JavaScript, two variables of different types can be combined. example: A = “ This apple costs Rs.” + 5 will result in a string with the value "This apple costs Rs. 10 JS Data Type - Example <HTML> <HEAD> <SCRIPT LANGUAGE = "Javascript"> var A = "12" + 7.write(A); </SCRIPT> </HEAD> </HTML> 11 JS Literal - Types  Integer – These can be expressed in decimal, hexadecimal and binary number system.  Floating- point - These number can have a decimal point or an “e” or “”E” followed by an integer.

 String - A string literal is zero or more characters enclosed in single or double quotation marks.  Boolean - This can take only two values: True or False.  null - The null type has only one value: null. Null implies no data.

12 Operators  Operators take one or more variables or values (operands) and return a new value.  JavaScript uses both binary and unary operators.  Operators are classified depending on the relation they perform like:  Arithmetic Operator: +, -, *, /, ++, --  Comparison Operator: ==, !=, >, >=, <, <=  Logical Operator: &&, ||, !  String Operator  Evaluation Operator  Operator Precedence 13 Evaluation Operator  These operators generally includes:  Conditional operator (condition) ? trueVal : falseVal Assigns a specified value to a variable if a condition is true, otherwise assigns an alternate value if condition is false. status = (age >= 18) ? "adult" : "minor"  Typeof operator The typeof operator returns a string indicating the type of the operand.write(typeof(x)); 14 Switch Statement  The switch statement works like in C#: switch (variable) { switch-statements.html case 1: // do something break; case 'a': // do something else break; case 3.14: // another code break; default: // something completely different } 15 Loop  Structures that control repetition in a program are known as loops.

 The various types of loops include:  For var counter;  Do …. While for (counter=0; counter<4; counter++) {  While alert(counter); }  Break & continue while (counter < 5) {  For….in alert(++counter);  with } 16 Function  JavaScript has several pre-defined functions that we can use within the script.  Some of pre-defined JavaScript functions includes:  eval function  isNaN funtion  Creating User Defined Functions function funcName(argument1,argument2,etc) { statements; }  Calling a Function  Return Statement 17 Function (1)  Code structure – splitting code into parts Parameters  Data comes in, processed, result returned come in here. function average(a, b, c) Declaring variables is { optional.

Type is never var total; declared. total = a+b+c; return total/3; } Value returned here. 18 Function Arguments and Return Value  Functions are not required to return a value  When calling function it is not obligatory to specify all of its arguments  The function has access to all the arguments passed via arguments array function sum() { var sum = 0; for (var i = 0; i < arguments.length; i ++) sum += parseInt(arguments[i]); return sum; } alert(sum(1, 2, 4)); 19 Standard Popup Boxes  Alert box with text and [OK] button  Just a message shown in a dialog box: alert("Some text here");  Confirmation box  Contains text, [OK] button and [Cancel] button: confirm("Are you sure?");  Prompt box  Contains text, input field with default value: prompt ("enter amount", 10); 20 JavaScript Prompt – Example price = prompt("Enter the price", "10.00"); alert('Price + VAT = ' + price * 1.2); 21 The Core language Objects in JavaScript 22 Objects In JavaScript, almost "everything" is an object.  Booleans can be objects (or primitive data treated as objects)  Numbers can be objects (or primitive data treated as objects)  Strings can be objects (or primitive data treated as objects)  Dates are always objects  Maths are always objects  Regular expressions are always objects  Arrays are always objects  Functions are always objects  Objects are objects  In JavaScript, all values, except primitive values, are objects.

23 Properties and Methods  To access the properties of the object, we must specify the object name and the property: objectName.propertyName  To access the methods of an object, we must specify the object name and the required method: objectName.method() 24 Using objects  When creating a Web page we can insert:  Browser objects  Built in script language objects (vary depending on the scripting language used)  HTML elements  We can also create our own objects for use in the programs.  Object Hierarchy Browser Objects Script Objects HTML Elements 25 String object  The string object is used to manipulate and work with strings of text.  We can extract substrings and convert text to upper- or lowercase characters in a program.  The general syntax is, stringName.propertyName or stringName.[,paramN]) where, objectName is the name of the new object instance.

objectType is a function that defined the type of the object. For example, Array. ] are the property values of the object 28 Create new Object  With JavaScript, you can define and create your own objects.  There are different ways to create new objects:  Define and create a single object, using an object literal.

 Define and create a single object, with the keyword new.  Define an object constructor, and then create objects of the constructed type.  Step 1: Create new object by create a function  Step 2: Create new instant by using new operator 29 Creating String object  There are 3 different methods of creating strings.  Using the var statement and optionally assigning it to a value.

 Using an assignment operator (=) with a variable name.  Using the string () constructor. <script type = "text/javascript"> var str = “Steve Paris!" document.length) var pos=str.write(pos + "<br />") } else { document. function Customer( iD,name,address) { this.CustomeriD = iD; //property this.CustomerName = name; //property this.CustomerAddress = address; //property this.Displayinfor = information; //method } function DisplayInfor () { document.write(“ID: ” + this.CustomeriD + ”<br>”); document.write(“Name: ” + this.CustomerName + ”<br>” document.write(“Address: ” + this.CustomerAddress + ”<br>” } 31 Create new Object – Example (2) Step 2.

var cust = new Customer(); cust.CustomerName= “Steve Paris” cust.CustomerAddress= “12 Orange Street”  In order to display customer’s information, we call Displayinfor() method: cust.Displayinfor() 32 Arrays Operations and Properties  Declaring new empty array: var arr = new Array();  Declaring an array holding few elements: var arr = [1, 2, 3, 4, 5];  Appending an element / getting the last element: arr.push(3); var element = arr.length;  Finding element's index in the array: arr.indexOf(1); 33 Math Object  The Math object has properties and methods that represent advanced mathematical calculations. <script> function doCalc(x) { var a; a = Math.PI * x * x; alert ("The area of a circle with a radius of " + x + “ is " + a); } </script> 34 Math Object Example for (i=1; i<=20; i++) { var x = Math.write("Random number (" + i + ") in range " + "1.10 --> " + x + "<br/>"); } 35 Date Object  The Date object provides date / calendar functions var now = new Date(); var result = "It is now " + now; document. <p id="timeField"></p> 36 Timers: setTimeout()  Make something happen (once) after a fixed delay var timer = setTimeout('bang()', 5000); 5 seconds after this statement executes, this function is called clearTimeout(timer); Cancels the timer 37 Timers: setInterval()  Make something happen repeatedly at fixed intervals var timer = setInterval('clock()', 1000); This function is called continuously per 1 second. clearInterval(timer); Stop the timer.

38 Date Object Example <html><head> <body BGCOLOR="#FFFFFF” onLoad="startclock()"> <title>Digital Clock - Status Bar</title> <script Language="JavaScript"> </body></html> var timeriD = null; var timerRunning = false; function stopclock (){ if(timerRunning) clearTimeout(timeriD); timerRunning = false; } function showtime () { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.status = timeValue; timeriD = setTimeout("showtime()",1000); timerRunning = true; 39 } Document Object Model (DOM) and The Browser Objects in JavaScript 40 Event Object - Concept  Events are a result of an action done by the user  An event may be user-generated or generated by the system  Each event has an associated event object. The event object provides information on:  the type of event  the location of the cursor at the time of the event  The event object is used as a part of an event handler 41 Event – Life Cycle  Events are a result of an action done by the user  An event may be user-generated or generated by the system  Each event has an associated event object. The event object provides information on:  the type of event  the location of the cursor at the time of the event  The event object is used as a part of an event handler 42 JavaScript Event  Common events supported by JavaScript includes:  onClick  onChange  onFocus  onBlur  onMouseOver  onMouseOut  onLoad  onSubmit  onMouseDown  onMouseUp 43 onClick - Example  The onClick event is generated whenever the user clicks the mouse button on certain form elements or on a hypertext link.

Nội dung được bảo vệ bản quyền — Tải xuống đầy đủ