user19575199
user19575199

Reputation:

HTML - how to import javascript and css to html file

I am quite new. How to import css file and javascript file, and what is a good file structure to learn when new to web dev?

Upvotes: 0

Views: 1718

Answers (3)

Lakshya Raj
Lakshya Raj

Reputation: 1775

Good file structure

As for the good file structure: include your JS and CSS files in an assets/ folder and/or in their own separate folders js/ and css/. Here's an example below:

index.html
otherpage.html
assets/
    js/
        main.js
        funcs.js
    css/
        global.css
        darkmode.css

To make it simpler, you could try

index.html
otherpage.html
js/
    main.js
    funcs.js
css/
    global.css
    darkmode.css

or

index.html
otherpage.html
assets/
    main.js
    funcs.js
    global.css
    darkmode.css

It's really up to you, based on how complex your project is. If you only have 3 files (HTML, CSS, and JS), you might not need any folder structuring at all. If you have 20... you should make sure everything is sorted out. You can also do this for images img/, fonts font/, and other things.

Including CSS

To include a CSS file into your HTML, insert the below in your head tag.

<link rel="stylesheet" href="./assets/css/global.css"/>

Also note that you need to change the href attribute to the actual file path to your CSS file.

Including JavaScript

For JavaScript, it's even simpler. Include this tag at the end of your body tag.

<script src="./assets/js/main.js"></script>

It's necessary to include both the start and end tags. Again, change the file path to your JS file.

Upvotes: 1

Sojo C Johny
Sojo C Johny

Reputation: 136

Use this < link > for css and put it in the head tag of html is preferred, here href has the path and name of the css file:

<link rel="stylesheet" href="/file.css">

Use the < script > for javascript and put it in the bottom of body tag is preferred, here src has the path and name of the js file:

<script type="text/javascript" src="file.js"></script>

Upvotes: 1

Alexandre Martin
Alexandre Martin

Reputation: 1502

Here is the HTML squeleton using CSS and JS :

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Page Title</title>
<link rel="stylesheet" href="linktoyourstylesheet.css">
<script type="text/javascript" src="linktoyourscript.js"></script>
<body>
    Main Content Here
</body>
</html>

At the same level as my index file, I have an asset folder which includes JS ans CSS folders.

Upvotes: 1

Related Questions