Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created June 13, 2023 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/d2b21c290e0b1d1e73661305f30408ec to your computer and use it in GitHub Desktop.
Save code-boxx/d2b21c290e0b1d1e73661305f30408ec to your computer and use it in GitHub Desktop.
Ways To Include Javascript In HTML

WAYS TO INCLUDE JAVASCRIPT IN HTML

https://code-boxx.com/javascript-in-html/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

alert("1A Loaded");
<!DOCTYPE html>
<html>
<head>
<title>JS In HTML</title>
<!-- (A) RELATIVE URL -->
<script src="1a-external.js"></script>
<!-- (B) ABSOLUTE URL -->
<script src="http://localhost/1a-external.js"></script>
</head>
<body></body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JS In HTML</title>
</head>
<body>
<p>Some HTML</p>
<script>
alert("Loaded");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JS In HTML</title>
</head>
<body>
<p onmouseover="alert('Mouse Over');">Hover to alert.</p>
<input type="button" value="Say Hello" onclick="alert('Hello World!');">
</body>
</html>
function demoA () {
alert("Demo A");
}
<!DOCTYPE html>
<html>
<head>
<title>JS In HTML</title>
<!-- (A) SCRIPT IN HEAD -->
<script src="4a-demo.js"></script>
</head>
<body>
<!-- (B) SCRIPT IN BODY -->
<script>
function demoB () {
alert("Demo B");
}
</script>
<!-- (C) HTML ELEMENTS -->
<p onclick="demoA()">Demo A</p>
<p onclick="demoB()">Demo B</p>
</body>
</html>
alert("First loaded");
alert("Second loaded");
<!DOCTYPE html>
<html>
<head>
<title>JS In HTML</title>
<!-- (A) THIS WILL LOAD FIRST -->
<script src="5a-first.js"></script>
</head>
<body>
<!-- (B) FOLLOWED BY HTML ELEMENTS -->
<p>Demo A</p>
<p>Demo B</p>
<!-- (C) THIS WILL LOAD LAST -->
<script src="5b-second.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment