Referenced javascript files should be included in the script tag. Use the src attribute of the script tag to specify the path to the external JavaScript file, with the syntax "".
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
Quoting JavaScript files
Like CSS files, JavaScript code can be stored in a separate file. To enhance the reproducible invocation of JavaScript scripts. A JavaScript file is a text file that can be opened and edited in any text editor. The extension of a JavaScript file is js.
<script> tag is used to define client-side scripts, such as JavaScript. The </script>
<script> element can either contain script statements or point to an external script file through the "src" attribute. </script>
When introducing a JavaScript file, you can use the <script> tag. Just specify the URL (Uniform Resource Locator) of the JavaScript file through the src attribute of the tag. </script>
Example:
Create a new text file, save it as test.js, and write a public function in the file to return the length of the string
//公共函数:计算字符串的实际长度 function strlen(str){ var len;//声明临时变量,存储字符串的实际长度 var i;//声明循环变量 len = 0;//初始化临时变量len为0 for(i = 0; i < str.length; i++){//循环检测字符串中每个字符 if(str.charCodeAt(i) > 255)//如果当前字符为双字节字符,+2 len += 2; else //如果当前字符为单字节字符,+1 len++; } return len;//返回实际长度值 }
Create a new html document and introduce test.js.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <!-- 引入外部JavaScript文件 --> <script type="text/javascript" src="test.js" ></script> </head> <script> var str = "JavaScript编程语言"; document.write("<h2>" + str + "</h2>");//输出变量的值 document.write("<p>实际长度=" + strlen(str) + "字节</p>");//调用函数 </script> <body> </body> </html>
Using external JavaScript files can enhance JavaScript modular development programs and improve code reuse. In web development, users should develop a good habit of code reuse. When writing JavaScript code, use more external JavaScript files, which can improve the speed and efficiency of project development.
Related recommendations: javascript learning tutorial
The above is the detailed content of Should the referenced javascript file be included in the script tag?. For more information, please follow other related articles on the PHP Chinese website!