Patrik
Patrik

Reputation: 69

How to run JS files on specific page

I have:

<body class="home">
  content
</body>

And then I have:

<script src="abs.js"></script>
<script src="abse.js"></script>
<script src="abses.js"></script>

I have these scripts in head and they are running on all pages. How I can run them on ".home" page only?

Thank you :-)

Upvotes: 2

Views: 3878

Answers (2)

Ramaiah Kethana
Ramaiah Kethana

Reputation: 105

You can solve the problem by writing a function and load scripts by checking whether the url is home page url or not. Check following code, it will helpful to you.

Note: Change website url to yours from /home/sys3028/Desktop/

/* loading scripts */
        loadingScripts();

        /* written by christyram99 */
        /* used to load scripts for specific page */
        function loadingScripts() {
            /* getting url of current page */
            var url = window.location.pathname;
            if (url == "/home/sys3028/Desktop/home.html") { /* checking whether the current page is home page or not */
                var script = document.createElement('script');
                script.src = "1.js";
            } else if (url == "/home/sys3028/Desktop/login.html") { /* checking whether the current page is login page or not */
                var script = document.createElement('script');
                script.src = "2.js";
            } else if (url == "/home/sys3028/Desktop/contact.html") { /* checking whether the current page is contact page or not */
                var script = document.createElement('script');
                script.src = "3.js";
            }
        }

Upvotes: 2

Quinten
Quinten

Reputation: 114

An HTML answer would be to only include them in the header of the homepage and remove the scripts from the other pages

Upvotes: 1

Related Questions