Search code examples
javascripthtmlejshoisting

Should I use script tag and style tag in ejs files?


I'm using ejs as my template engine with node.js, and I'm using ejs as different components for my pages, e.g. homepage might be composed of header.ejs + sidebar.ejs + main.ejs, each representing a different part of the page.

Each ejs file has its own CSS and JavaScript, and I'm using script tag and style tag in these ejs files directly.

This works fine now, but the rendered HTML looks kind of weird, e.g. there might be <style> tags and <script> tags alternate in several place of HTML body.

I'm wondering would this cause some kind of async execution problem, or any unexpected error, or would it works fine due to hoisting.


Solution

  • Yes, you can use it, but lets see first what is use of EJS files.

    • EJS is one of the most popular template engines for JavaScript.
    • If you want to render a static page then go for an HTML file and if you want to render a dynamic page where your comes from various sources then you must choose an EJS file.

    keep CSS files in separate folders/files, and import them in your ejs file as follows :

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

    we can also add CSS in <style></style> tag in head tag.

    JS code add-in script tag as follows :

    <script>
        const userAction = async () => {
           const res = await fetch('api/abc/id');
           const json = await res.json();
        }
    </script>