External JavaScript File - 4.2.2 | Chapter 4: JavaScript Basics – Making Webpages Interactive | Full Stack Web Development Basics
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

games

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to External JavaScript

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we're going to learn about using external JavaScript files. Do you remember why we use JavaScript in the first place? It makes our webpages interactive!

Student 1
Student 1

Yes! It helps with things like validating forms and making menus drop down.

Teacher
Teacher

Exactly! Now, can anyone tell me what you think would happen if we kept all our JavaScript code inside our HTML files?

Student 2
Student 2

It would get messy and hard to read!

Student 3
Student 3

And it could slow down the loading times, right?

Teacher
Teacher

Yes! That's why using an external JavaScript file is beneficial. It keeps our HTML clean and improves the organization. Let's see how we do that.

Student 4
Student 4

How do we link an external file?

Teacher
Teacher

Great question! You link it using the `<script>` tag with the `src` attribute. For example: `<script src="script.js"></script>`. Remember, it’s best practice for larger projects!

Teacher
Teacher

To recap, using external JavaScript files keeps our HTML organized and helps with loading times. Let's move to the next session!

Loading JavaScript Files

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now that we can link our JavaScript, when do you think is the best time to load it in our HTML document?

Student 2
Student 2

Maybe at the top, so it loads first?

Student 1
Student 1

Or at the bottom to make sure all the HTML is ready first!

Teacher
Teacher

You’re right! It’s often better to place your `<script>` tag just before the closing `</body>` tag to ensure everything is loaded first. This avoids blocking the page rendering.

Student 4
Student 4

What if I want to run a script as soon as the page loads?

Teacher
Teacher

Good point! You can also use the `defer` attribute which ensures the script is executed after the document has been parsed. Remember that linking external scripts allows for reusability across different HTML documents!

Teacher
Teacher

Recap this session: Link scripts at the bottom of your HTML or use `defer`. Always think about loading order to enhance performance!

Advantages of External Scripts

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Let’s discuss some advantages of using external JavaScript files. Can anyone list a few benefits?

Student 3
Student 3

It makes it easier to find and fix bugs!

Student 2
Student 2

And we can reuse the code across multiple pages!

Teacher
Teacher

Exactly! By separating the JavaScript, we promote reusability and easier maintenance, especially in collaboration where different developers can work on different parts.

Student 1
Student 1

Does that mean if I change the external file, all pages using it will update?

Teacher
Teacher

Absolutely! Just remember, always comment your code for clarity! Who can tell me a disadvantage of external scripts?

Student 4
Student 4

Maybe loading speed if it’s not cached?

Teacher
Teacher

Yes! The initial load might be affected if the file isn’t cached. But overall, the benefits greatly outweigh the disadvantages. Remember: ‘Separate to Conquer’ when it comes to code organization!

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

An external JavaScript file allows developers to keep their JavaScript code separate from HTML, leading to cleaner code organization.

Standard

Using external JavaScript files makes it easier to manage and maintain code, especially in larger projects. By linking a separate .js file to an HTML document, developers can load scripts without cluttering the HTML structure, allowing for better organization.

Detailed

External JavaScript File

When building websites, it's highly effective to use external JavaScript files to keep your JavaScript code separate from your HTML code. This practice enhances code maintainability and allows for easier updates and debugging.

To incorporate an external JavaScript file, you simply link it in your HTML file using the <script> tag with a src attribute pointing to the .js file. For example:

Code Editor - html

This is an external script

`, -1); codePreview9dccf9a070714e5f8a539e7bbf904d47.setTheme('ace/theme/textmate'); // Attach try it yourself button listener document.getElementById(`try-it-9dccf9a070714e5f8a539e7bbf904d47`).addEventListener('click', () => { switchToEditor9dccf9a070714e5f8a539e7bbf904d47(); }); function switchToEditor9dccf9a070714e5f8a539e7bbf904d47() { // Initialize the editor editor9dccf9a070714e5f8a539e7bbf904d47 = ace.edit("9dccf9a070714e5f8a539e7bbf904d47") setLanguage9dccf9a070714e5f8a539e7bbf904d47(language9dccf9a070714e5f8a539e7bbf904d47); editor9dccf9a070714e5f8a539e7bbf904d47.setValue(`

This is an external script

`, -1); initEditorSettings9dccf9a070714e5f8a539e7bbf904d47(); attachEventListeners9dccf9a070714e5f8a539e7bbf904d47(); document.getElementById(`editor-container-9dccf9a070714e5f8a539e7bbf904d47`).classList.remove('hidden'); document.getElementById(`preview-container-9dccf9a070714e5f8a539e7bbf904d47`).classList.add('hidden'); } function switchToPreview9dccf9a070714e5f8a539e7bbf904d47() { // Clean up the editor instance editor9dccf9a070714e5f8a539e7bbf904d47.destroy(); editor9dccf9a070714e5f8a539e7bbf904d47 = null; document.getElementById(`editor-container-9dccf9a070714e5f8a539e7bbf904d47`).classList.add('hidden'); document.getElementById(`preview-container-9dccf9a070714e5f8a539e7bbf904d47`).classList.remove('hidden'); // Reattach the try it yourself button listener document.getElementById(`try-it-9dccf9a070714e5f8a539e7bbf904d47`).addEventListener('click', () => { switchToEditor9dccf9a070714e5f8a539e7bbf904d47(); }); } function initEditorSettings9dccf9a070714e5f8a539e7bbf904d47() { editor9dccf9a070714e5f8a539e7bbf904d47.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }); editor9dccf9a070714e5f8a539e7bbf904d47.setTheme('ace/theme/xcode'); editor9dccf9a070714e5f8a539e7bbf904d47.session.setMode(`ace/mode/${language9dccf9a070714e5f8a539e7bbf904d47}`); } function setLanguage9dccf9a070714e5f8a539e7bbf904d47(lang) { language9dccf9a070714e5f8a539e7bbf904d47 = lang; editor9dccf9a070714e5f8a539e7bbf904d47.session.setMode(`ace/mode/${lang}`); } // Add method to update code programmatically function setCode9dccf9a070714e5f8a539e7bbf904d47(code) { editor9dccf9a070714e5f8a539e7bbf904d47.setValue(code, -1); } function toggleTheme9dccf9a070714e5f8a539e7bbf904d47() { const isDarkMode = editor9dccf9a070714e5f8a539e7bbf904d47.getTheme() === 'ace/theme/monokai'; const sunIcon = document.getElementById(`theme-icon-9dccf9a070714e5f8a539e7bbf904d47`); const moonIcon = document.getElementById(`moon-icon-9dccf9a070714e5f8a539e7bbf904d47`); if (isDarkMode) { editor9dccf9a070714e5f8a539e7bbf904d47.setTheme('ace/theme/xcode'); sunIcon.classList.remove('hidden'); moonIcon.classList.add('hidden'); } else { editor9dccf9a070714e5f8a539e7bbf904d47.setTheme('ace/theme/monokai'); sunIcon.classList.add('hidden'); moonIcon.classList.remove('hidden'); } } function removeTrailingSpaces(base64String) { // Trim the string to remove any trailing newline characters return btoa(atob(base64String).trim()); } async function runCode9dccf9a070714e5f8a539e7bbf904d47() { const code = btoa(editor9dccf9a070714e5f8a539e7bbf904d47.getValue()); const stdIn = btoa(document.getElementById("input-9dccf9a070714e5f8a539e7bbf904d47").value); const loader = document.getElementById(`run-loader-9dccf9a070714e5f8a539e7bbf904d47`); const output = document.getElementById(`output-9dccf9a070714e5f8a539e7bbf904d47`); const outputContainer = document.getElementById(`run-output-9dccf9a070714e5f8a539e7bbf904d47`); const batchOutputContainer = document.getElementById(`batch-run-output-9dccf9a070714e5f8a539e7bbf904d47`); loader.classList.remove('hidden'); outputContainer.classList.remove('hidden'); output.innerHTML = ''; try { const response = await fetch('/code/api/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: language9dccf9a070714e5f8a539e7bbf904d47, language_id: getLanguageId9dccf9a070714e5f8a539e7bbf904d47(language9dccf9a070714e5f8a539e7bbf904d47), source_code: code, std_in: stdIn, submission_type: 'run', test_cases: [] || [], }), }); const codeResult = await response.json(); if (Array.isArray(codeResult)) { outputContainer.classList.add("hidden"); batchOutputContainer.classList.remove("hidden"); batchOutputContainer.innerHTML = `
${codeResult?.map((result, index) => { const testCaseStatus = result.is_public ? removeTrailingSpaces(result.stdout) === result.expected_output : result.status; return `
${testCaseStatus ? `` : ``} Test Case ${index + 1} ${!result.is_public ? `` : ``}
`; }) .join("")}
${codeResult && codeResult[0] ? atob(codeResult[0].stdin) : "No input available"}
${codeResult && codeResult[0] ? atob(codeResult[0].expected_output) : "No expected output available"}
${codeResult?.[0]?.stderr || codeResult[0].compile_output ? atob(codeResult[0].stderr || codeResult[0].compile_output) : codeResult?.[0] ? (codeResult[0].stdout == null ? "" : atob(codeResult[0].stdout)) : "No output available"}
`; codeResult?.forEach((result, index) => { const codeResult = result; document.getElementById(`testCase-${index}`).addEventListener("click", () => { Array.from(document.querySelectorAll('[id*="testCase"]'))?.map(testCase => { if (testCase.id === `testCase-${index}`) { testCase.classList.add("lg:scale-105", "border", "border-gray-200"); testCase.classList.remove("scale-100", "border-none"); } else { testCase.classList.add("scale-100", "border-none"); testCase.classList.remove("lg:scale-105", "border", "border-gray-200"); } }) if (!result.is_public) { document.getElementById("test-result").innerHTML = `

Hidden Test Case

` return; } document.getElementById("test-result").innerHTML = `
${codeResult ? atob(codeResult.stdin) : "No input available"}
${codeResult ? atob(codeResult.expected_output) : "No expected output available"}
${codeResult ? (codeResult.stderr || codeResult.compile_output ? atob(codeResult.stderr || codeResult.compile_output) : codeResult.stdout == null ? "" : atob(codeResult.stdout)) : "No output available"}
`; }); }); } else { batchOutputContainer.classList.add("hidden") outputContainer.classList.remove('hidden') output.textContent = codeResult.stderr ? atob(codeResult.stderr) : atob(codeResult.stdout || ''); } } catch (error) { console.error(error); } finally { loader.classList.add('hidden'); } } function getLanguageId9dccf9a070714e5f8a539e7bbf904d47(language) { const languages = { javascript: 63, python: 71, java: 62, c_cpp: 49, }; return languages[language]; } function attachEventListeners9dccf9a070714e5f8a539e7bbf904d47() { document .getElementById(`theme-toggle-9dccf9a070714e5f8a539e7bbf904d47`) .addEventListener('click', toggleTheme9dccf9a070714e5f8a539e7bbf904d47); document .getElementById(`run-code-9dccf9a070714e5f8a539e7bbf904d47`) .addEventListener('click', runCode9dccf9a070714e5f8a539e7bbf904d47); document .getElementById(`view-preview-9dccf9a070714e5f8a539e7bbf904d47`) .addEventListener('click', switchToPreview9dccf9a070714e5f8a539e7bbf904d47); }

In this HTML snippet, the JavaScript file script.js is referenced, which can contain various scripts including function definitions, events, and other functionalities. This method is particularly recommended for larger projects where managing extensive amounts of code in a single file can become unwieldy.

Using external files not only keeps HTML pages cleaner but also promotes code reusability and separation of concerns, making it easier for multiple developers to collaborate on a single project.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Linking External JavaScript File

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

You can also write JavaScript in a separate .js file and link it in your HTML:
HTML:

Code Editor - html

This is an external script

`, -1); codePreview11c8ad4b293b42d5a292586719f84c9d.setTheme('ace/theme/textmate'); // Attach try it yourself button listener document.getElementById(`try-it-11c8ad4b293b42d5a292586719f84c9d`).addEventListener('click', () => { switchToEditor11c8ad4b293b42d5a292586719f84c9d(); }); function switchToEditor11c8ad4b293b42d5a292586719f84c9d() { // Initialize the editor editor11c8ad4b293b42d5a292586719f84c9d = ace.edit("11c8ad4b293b42d5a292586719f84c9d") setLanguage11c8ad4b293b42d5a292586719f84c9d(language11c8ad4b293b42d5a292586719f84c9d); editor11c8ad4b293b42d5a292586719f84c9d.setValue(`

This is an external script

`, -1); initEditorSettings11c8ad4b293b42d5a292586719f84c9d(); attachEventListeners11c8ad4b293b42d5a292586719f84c9d(); document.getElementById(`editor-container-11c8ad4b293b42d5a292586719f84c9d`).classList.remove('hidden'); document.getElementById(`preview-container-11c8ad4b293b42d5a292586719f84c9d`).classList.add('hidden'); } function switchToPreview11c8ad4b293b42d5a292586719f84c9d() { // Clean up the editor instance editor11c8ad4b293b42d5a292586719f84c9d.destroy(); editor11c8ad4b293b42d5a292586719f84c9d = null; document.getElementById(`editor-container-11c8ad4b293b42d5a292586719f84c9d`).classList.add('hidden'); document.getElementById(`preview-container-11c8ad4b293b42d5a292586719f84c9d`).classList.remove('hidden'); // Reattach the try it yourself button listener document.getElementById(`try-it-11c8ad4b293b42d5a292586719f84c9d`).addEventListener('click', () => { switchToEditor11c8ad4b293b42d5a292586719f84c9d(); }); } function initEditorSettings11c8ad4b293b42d5a292586719f84c9d() { editor11c8ad4b293b42d5a292586719f84c9d.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }); editor11c8ad4b293b42d5a292586719f84c9d.setTheme('ace/theme/xcode'); editor11c8ad4b293b42d5a292586719f84c9d.session.setMode(`ace/mode/${language11c8ad4b293b42d5a292586719f84c9d}`); } function setLanguage11c8ad4b293b42d5a292586719f84c9d(lang) { language11c8ad4b293b42d5a292586719f84c9d = lang; editor11c8ad4b293b42d5a292586719f84c9d.session.setMode(`ace/mode/${lang}`); } // Add method to update code programmatically function setCode11c8ad4b293b42d5a292586719f84c9d(code) { editor11c8ad4b293b42d5a292586719f84c9d.setValue(code, -1); } function toggleTheme11c8ad4b293b42d5a292586719f84c9d() { const isDarkMode = editor11c8ad4b293b42d5a292586719f84c9d.getTheme() === 'ace/theme/monokai'; const sunIcon = document.getElementById(`theme-icon-11c8ad4b293b42d5a292586719f84c9d`); const moonIcon = document.getElementById(`moon-icon-11c8ad4b293b42d5a292586719f84c9d`); if (isDarkMode) { editor11c8ad4b293b42d5a292586719f84c9d.setTheme('ace/theme/xcode'); sunIcon.classList.remove('hidden'); moonIcon.classList.add('hidden'); } else { editor11c8ad4b293b42d5a292586719f84c9d.setTheme('ace/theme/monokai'); sunIcon.classList.add('hidden'); moonIcon.classList.remove('hidden'); } } function removeTrailingSpaces(base64String) { // Trim the string to remove any trailing newline characters return btoa(atob(base64String).trim()); } async function runCode11c8ad4b293b42d5a292586719f84c9d() { const code = btoa(editor11c8ad4b293b42d5a292586719f84c9d.getValue()); const stdIn = btoa(document.getElementById("input-11c8ad4b293b42d5a292586719f84c9d").value); const loader = document.getElementById(`run-loader-11c8ad4b293b42d5a292586719f84c9d`); const output = document.getElementById(`output-11c8ad4b293b42d5a292586719f84c9d`); const outputContainer = document.getElementById(`run-output-11c8ad4b293b42d5a292586719f84c9d`); const batchOutputContainer = document.getElementById(`batch-run-output-11c8ad4b293b42d5a292586719f84c9d`); loader.classList.remove('hidden'); outputContainer.classList.remove('hidden'); output.innerHTML = ''; try { const response = await fetch('/code/api/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: language11c8ad4b293b42d5a292586719f84c9d, language_id: getLanguageId11c8ad4b293b42d5a292586719f84c9d(language11c8ad4b293b42d5a292586719f84c9d), source_code: code, std_in: stdIn, submission_type: 'run', test_cases: [] || [], }), }); const codeResult = await response.json(); if (Array.isArray(codeResult)) { outputContainer.classList.add("hidden"); batchOutputContainer.classList.remove("hidden"); batchOutputContainer.innerHTML = `
${codeResult?.map((result, index) => { const testCaseStatus = result.is_public ? removeTrailingSpaces(result.stdout) === result.expected_output : result.status; return `
${testCaseStatus ? `` : ``} Test Case ${index + 1} ${!result.is_public ? `` : ``}
`; }) .join("")}
${codeResult && codeResult[0] ? atob(codeResult[0].stdin) : "No input available"}
${codeResult && codeResult[0] ? atob(codeResult[0].expected_output) : "No expected output available"}
${codeResult?.[0]?.stderr || codeResult[0].compile_output ? atob(codeResult[0].stderr || codeResult[0].compile_output) : codeResult?.[0] ? (codeResult[0].stdout == null ? "" : atob(codeResult[0].stdout)) : "No output available"}
`; codeResult?.forEach((result, index) => { const codeResult = result; document.getElementById(`testCase-${index}`).addEventListener("click", () => { Array.from(document.querySelectorAll('[id*="testCase"]'))?.map(testCase => { if (testCase.id === `testCase-${index}`) { testCase.classList.add("lg:scale-105", "border", "border-gray-200"); testCase.classList.remove("scale-100", "border-none"); } else { testCase.classList.add("scale-100", "border-none"); testCase.classList.remove("lg:scale-105", "border", "border-gray-200"); } }) if (!result.is_public) { document.getElementById("test-result").innerHTML = `

Hidden Test Case

` return; } document.getElementById("test-result").innerHTML = `
${codeResult ? atob(codeResult.stdin) : "No input available"}
${codeResult ? atob(codeResult.expected_output) : "No expected output available"}
${codeResult ? (codeResult.stderr || codeResult.compile_output ? atob(codeResult.stderr || codeResult.compile_output) : codeResult.stdout == null ? "" : atob(codeResult.stdout)) : "No output available"}
`; }); }); } else { batchOutputContainer.classList.add("hidden") outputContainer.classList.remove('hidden') output.textContent = codeResult.stderr ? atob(codeResult.stderr) : atob(codeResult.stdout || ''); } } catch (error) { console.error(error); } finally { loader.classList.add('hidden'); } } function getLanguageId11c8ad4b293b42d5a292586719f84c9d(language) { const languages = { javascript: 63, python: 71, java: 62, c_cpp: 49, }; return languages[language]; } function attachEventListeners11c8ad4b293b42d5a292586719f84c9d() { document .getElementById(`theme-toggle-11c8ad4b293b42d5a292586719f84c9d`) .addEventListener('click', toggleTheme11c8ad4b293b42d5a292586719f84c9d); document .getElementById(`run-code-11c8ad4b293b42d5a292586719f84c9d`) .addEventListener('click', runCode11c8ad4b293b42d5a292586719f84c9d); document .getElementById(`view-preview-11c8ad4b293b42d5a292586719f84c9d`) .addEventListener('click', switchToPreview11c8ad4b293b42d5a292586719f84c9d); }

script.js:

Code Editor - javascript

Detailed Explanation

This chunk explains how to link an external JavaScript file to your HTML document. Instead of embedding JavaScript directly in your HTML, you can write it in a separate file, usually with a .js extension. In the HTML portion, a

Examples & Analogies

Think of linking an external JavaScript file like having a recipe book in your kitchen. Instead of writing the whole recipe on your kitchen wall (embedding), you can just refer to the book (external reference) whenever you need to check the instructions on how to cook something. This keeps your kitchen tidy and the wall clear, just like keeping your HTML clean and organized when you use external scripts.

Advantages of External JavaScript

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

🟡 Using external files is better for large projects.

Detailed Explanation

Using external JavaScript files instead of internal scripts has significant benefits, especially for larger projects. With external files, you can keep your HTML and JavaScript code separate, making both easier to manage and update. If multiple HTML files need the same JavaScript functionality, you can link to the same JavaScript file rather than copying the script into each HTML file. This reduces redundancy, improves load times, as the browser can cache the JavaScript file, and eases collaboration among developers, as everyone can work on different files independently.

Examples & Analogies

Imagine you're part of a group project in school. Instead of everyone writing their part of the project report in one notebook, each person works on their section in separate notebooks. Later, you can combine all the notebooks into a single presentation. This way, it's easier to review, edit, and present, similar to how using external JavaScript files keeps code organized and manageable.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • External JavaScript: Allows separation of JavaScript code from HTML for better organization.

  • Script Tag: Used to link external JavaScript files through the src attribute.

  • Defer Attribute: Ensures scripts load after the HTML is parsed to improve performance.

  • Maintainability: Refers to the ease of making updates and modifications to the code.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • Linking a JavaScript file using in an HTML document.

  • Using the defer attribute like to optimize loading.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • Load scripts later, keep HTML neat, / Keeps the site speedy, that's no defeat!

📖 Fascinating Stories

  • Once there was a web developer named Alex who cluttered their HTML so much with scripts that the pages took forever to load. One day, a wise mentor advised Alex to separate their JavaScript into external files, and lo! The pages became faster, and Alex’s code became much cleaner.

🧠 Other Memory Gems

  • Remember the word 'CLOAK': C for Clean code, L for Load performance, O for Organization, A for Accessibility, K for Keep it reusable – that's the power of external scripts!

🎯 Super Acronyms

Think of 'LESS' which stands for

  • Link
  • Execute
  • Separate
  • and Simplify for JavaScript organization.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: External JavaScript File

    Definition:

    A separate file containing JavaScript code that can be linked to an HTML document using a <script> tag.

  • Term: src attribute

    Definition:

    An attribute in the <script> tag that specifies the URL of an external JavaScript file.

  • Term: defer

    Definition:

    An attribute that allows the script to be executed after the document has been completely parsed.

  • Term: Maintainability

    Definition:

    The ease of managing and updating code in a software project.