I was wondering what would be the best way to execute a java-script code only on specific pages.
Let\'s imagine we have a template-based web-site, rewrite rule for t
I would use the switch statement and a variable. (I'm using jQuery!)
var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch(windowLoc){
case "/info.php":
//code here
break;
case "/alert.php":
//code here
break;
}
//use windowLoc as necessary elsewhere
This will allow you to change what "button" does based on the page that you're on. If I understood your question correctly; this is what I would do. Also, if I had were serving large amounts of javascript, I would simply add a new JS file completely.
var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch(windowLoc){
case "/info.php":
var infoJS = document.createElement('script');
infoJS.type = 'text/javascript';
infoJS.src = 'location/to/my/info_file.js';
$('body').append(infoJs);
break;
case "/alert.php":
var alertJS = document.createElement('script');
alertJS.type = 'text/javascript';
alertJS.src = 'location/to/my/alert_file.js';
$('body').append(alertJs);
break;
}
Hope this helps -
Cheers.
You can use Require js (RequireJS is a JavaScript file and module loader) and load script if they only needed. Link is http://requirejs.org/, I know using require js not so much easy.
A little different approach than checking the URL path : You can group page specific event handlers in a single function and then in each include, have a domready which will call these functions.
Eg: in script.js
you have two functions (outside domready) viz. onPage1Load()
and onPage2Load()
.
While in your page1.php
you have a $(document).ready(onPage1Load)
and so on for other pages. This will make sure that unintended event handlers are not registered.
Set a class
attribute to your body tag.
<body class="PageType">
And then in your script..
$(function(){
if($('body').is('.PageType')){
//add dynamic script tag using createElement()
OR
//call specific functions
}
});