0

In my web page I have some pages as /home, /about, /gallery, /contact.

On the I have a script as main.js . In this main.js script I have written some functions. Many of them is for all pages and just one function I don't want to enter to home page, is there any solution so I can control to which page which functions runs!

Actually want Im asking is, can I make this control by main Id or main class as > if on page exist #homepage don execute else execute , or similir to this idea ?

my king regards,

3 Answers 3

2

Can add a class (or classes) to the body tag that represents the page type(s).

Something like:

<body class="home">

Then check for that class:

function homePageOnly(){
  // home page only code
}

if($('body.home').length){
    homePageOnly();
}
Sign up to request clarification or add additional context in comments.

Comments

0

The JavaScript would be:

<script type="text/javascript">
    //about
    if(window.location.pathname == '/about') {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'path/to/main.js';
        head.appendChild(script);
    }

    //gallery
    if(window.location.pathname == '/gallery') {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'path/to/gallery.js';
        head.appendChild(script);
    }
</script>

Comments

0

Yes you can, create a separate file with individual scripts and then just import that file to the page that you want to execute such sript as <script type="text/javascript" src="path/to/script.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.