Inline JavaScript Code vs External JavaScript File

By:    Updated: January 23,2017

Although it's possible to embed JavaScript in HTML files directly, it's generally considered a best practice to include as much JavaScript as possible using external files. Keeping in mind that there are no hard and fast rules regarding this practice, the arguments for using external files are as follows:

<!DOCTYPE html>
<html>
<head>
    <title>Inline javascript code VS external javascript file</title>
</head>
<body>
    <!-- Inline javascript code -->
    <script type="text/javascript">
        alert("This is Inline javascript code");
    </script>
    <!-- external javascript file -->
    <script type="text/javascript" src="valinv_1.js"></script>
</body>
</html>

Maintainability

JavaScript code that is sprinkled throughout various HTML pages turns code maintenance into a problem. It is much easier to have a directory for all JavaScript files so that developers can edit JavaScript code independent of the markup in which it’s used.

 

Caching and Compress

1. Browsers cache all externally linked JavaScript files according to specific settings, meaning that if two pages are using the same file, the file is downloaded only once.This ultimately means faster page-load times.

2. CDN cache the external files with version number

3. Compress the files with server's gzip compress.

 

More in Development Center
New on Valinv
Related Articles
Sponsored Links