file1.html:
<!doctype html>
<body>
....
<script src=file.js></script>
<script>
// some code
</script>
</body>
file2.html:
<!doctype html>
<body>
....
<script src=file.js></script>
<script>
// different code
</script>
</body>
You can also check the location or the DOM in your JavaScript but the above is as simple as it gets.
Other ways, in file.js:
if (location.href == 'something') {
// do something
} else {
// do something else
}
Or, using jQuery:
jQuery(document).ready(function($) {
if ( $('h1').text() == 'Main Page' ) {
$('nav').hide();
$('#welcome').show();
} else {
// something ...
}
});
Page type 1:
<html>
<body class="one">
...Markup...
</body>
</html>
Page type 2:
<html>
<body class="two">
...Markup...
</body>
</html>
jQuery:
$().ready(function()
{
...code for all pages...
if($('body').hasClass('one'))
{
...code for pages of type 1...
}
else if($('body').hasClass('two'))
{
...code for pages of type 2...
}
...code for all pages...
});
I'm far from being a JavaScript guru, so I don't know how you might do this in pure JS. As rsp says, you could also split your code into separate files - one for code that will be needed in all pages, and files with page specific code which are only loaded on the page where they're required.
精彩评论