Search code examples
javascriptjqueryhtmlexternal

Load external script after page is done loading by using $(document).ready() and $.getScript()


As the title says I want to load a script by having my script tag on the header of the website and not the bottom of it.

A short example/attempt of mine would be this:

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="js/jquery-3.3.1.js">
        $(document).ready( function () {
            $.getScript("./js/script.js");
        } );
    </script>
   </head>
<body>
    <p id="para">hey there waht's up</p>
<body>
</html>

External JS file:

$("#para").click( function () {
    $("#para").hide();
})

But it doesn't work. Any idea why? Am I chasing unicorns?


Solution

  • As per the MDN documentation:

    If a script element has a src attribute specified, it should not have a script embedded inside its tags.

    So move the code to a separate script tag.

    <script src="js/jquery-3.3.1.js"></script> 
    <script> 
        $(document).ready( function () { $.getScript("./js/script.js"); } );
    </script>