1

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?

Not Amused
  • 942
  • 2
  • 10
  • 28

1 Answers1

2

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>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Thanks for your reply. I did what you suggested but it still wont work. So just to test that I have no mistakes in the code somewhere I added the script import at the bottom of body section and it worked. Something else I might be missing? – Not Amused Apr 08 '19 at 11:18
  • `jquery-3.3.1.js:9600 Access to XMLHttpRequest at 'file:///home/deus/Projects/web/test_jquery/js/script.js?_=1554722417976' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.` I guess $.getScript doesn't work for local files. – Not Amused Apr 08 '19 at 11:22
  • @DeusDeceit : https://stackoverflow.com/questions/20041656/xmlhttprequest-cannot-load-file-cross-origin-requests-are-only-supported-for-ht – Pranav C Balan Apr 08 '19 at 11:24
  • Yup, when served through apache it works. Thank you very much for your help. – Not Amused Apr 08 '19 at 11:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191447/discussion-between-pranav-c-balan-and-deus-deceit). – Pranav C Balan Apr 08 '19 at 11:42