For example I want to add some features to google.com home page and google.com search results page, and I want to do it in one greasemonkey script, I do:
@include http://google.com*
Then I check, if it's homepage, I add the third button under search box for example, if it's the results page I change font or something like that.
What would be the best way to differentiate between these pages? I currently do
if (document.URL==="homepage") {
add button
} else if (document.URL==="searchpage") {
change font
}
would switch be better? is there a better solution?
switch
is faster and more efficient than a series if/else if
I often use is for that purpose.
// caching path is faster (although the difference is only milliseconds)
var path = location.pathname;
switch (true) {
/* ----- Home page ----- */
case path.indexOf('/path1') !== -1:
addButton();
break;
/* ----- Search page ----- */
case path.indexOf('/path2') !== -1:
changeFont();
break;
}
Update:
Using ES6 includes()
var path = location.pathname;
switch (true) {
/* ----- Home page ----- */
case path.includes('/path1'):
addButton();
break;
/* ----- Search page ----- */
case path.includes('/path2'):
changeFont();
break;
}