KandZ – Tuts

We like to help…!

JavaScript 2 🧬 How to add JavaScript

2 – How to add JavaScript

1. How to Embed JavaScript in HTML Head Section

<head>
    <script>
        function greet() {
            alert('Hello from head!');
        }
    </script>
</head>
  • Place JavaScript code between <script> tags inside the <head> element

2. How to Embed JavaScript in HTML Body Section

<body>
    <button onclick="greet()">Click me</button>
    <script>
        function greet() {
            alert('Hello from body!');
        }
    </script>
</body>
  • Place JavaScript code after HTML elements in the <body> section

3. How to Link External JavaScript File

<head>
    <script src="scripts/main.js"></script>
</head>
  • Use src attribute to point to external JavaScript file

4. How to Add Event Listener Instead of Inline Handler

<button id="myButton">Click me</button>
<script>
    document.getElementById('myButton').addEventListener('click', function() {
        alert('Hello!');
    });
</script>
  • Replace onclick="function()" with addEventListener() method

5. How to Place JavaScript Before Closing Body Tag

<body>
    <h1>Hello World</h1>
    <script>
        console.log('Page loaded');
    </script>
</body>
  • Put script tags just before </body> for better performance

6. How to Add Multiple Scripts in One File

<script src="path/to/script1.js"></script>
<script src="path/to/script2.js"></script>
  • Include multiple <script> tags with different src attributes

7. How to Use Script Type Attribute

<script type="text/javascript">
    // JavaScript code here
</script>
  • Specify script type (though modern browsers default to JavaScript)

8. How to Add Async Script Loading

<script async src="script.js"></script>
  • Use async attribute for non-blocking script loading

9. How to Add Defer Script Loading

<script defer src="script.js"></script>
  • Use defer attribute to execute after HTML parsing

10. How to Create Function in External File

// main.js
function showMessage() {
    alert('External file function');
}
  • Define functions in separate .js files

11. How to Call External Function from HTML

<script src="main.js"></script>
<button onclick="showMessage()">Click</button>
  • Link external JS and call its functions in HTML

12. How to Use Document Ready Method

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Code here executes after DOM is ready
        alert('DOM ready');
    });
</script>
  • Wait for DOM to be fully loaded before executing code

13. How to Add JavaScript Without src Attribute

<script>
    var message = "Hello World";
    console.log(message);
</script>
  • Embed inline JavaScript without linking external files

14. How to Use Script Tag in Head for Early Execution

<head>
    <script>
        window.onload = function() {
            alert('Page fully loaded');
        };
    </script>
</head>
  • Place JavaScript in head for early execution

15. How to Add Multiple Event Listeners

<script>
    const button = document.getElementById('myButton');
    button.addEventListener('click', handleClick);
    button.addEventListener('mouseover', handleHover);

    function handleClick() { alert('Clicked'); }
    function handleHover() { console.log('Hovered'); }
</script>
  • Attach multiple event listeners to same element

16. How to Use Script Tag with Type Module

<script type="module" src="main.js"></script>
  • Use ES6 modules for modern JavaScript

17. How to Add Error Handling to External Scripts

<script src="script.js" onerror="console.log('Script failed')"></script>
  • Add error handling for external script loading

18. How to Use Self-Closing Script Tag

<script src="script.js"/>
  • Use self-closing format for external scripts (HTML5)

19. How to Add JavaScript to Specific Page Sections

<body>
    <section id="header">
        <script>console.log('Header section'); </script>
    </section>
</body>
  • Place scripts within specific HTML sections

20. How to Create Multiple Functions in External File

// utils.js
function validateForm() { return true; }
function calculateTotal() { return 100; }
function formatCurrency() { return '$100'; }
  • Organize multiple functions in one external file

21. How to Use Script Tag with Cross-Origin

<script src="https://cdn.example.com/script.js"></script>
  • Load scripts from external domains using full URLs

22. How to Add JavaScript Before DOM Elements

<body>
    <script>
        alert('Before content');
    </script>
    <h1>Content after script</h1>
</body>
  • Place script before HTML elements to execute first

23. How to Use Script in Footer for Better Performance

<footer>
    <script>
        // Heavy processing here
        console.log('Footer script');
    </script>
</footer>
  • Add scripts in footer for better page rendering

24. How to Combine Inline and External Scripts

<script>
    var inlineVar = 'value';
</script>
<script src="external.js"></script>
  • Mix both inline and external script loading

25. How to Add Conditional JavaScript Loading

<script>
    if (Modernizr.websockets) {
        // Load WebSocket script
        document.write('<script src="websocket.js"><\/script>');
    }
</script>
  • Conditionally load different scripts based on browser support

Leave a Reply