Reputation: 41
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,
Upvotes: 0
Views: 2760
Reputation: 219
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>
Upvotes: 0
Reputation: 171698
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();
}
Upvotes: 2
Reputation: 4205
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>
Upvotes: 0