J'ai créé une fonction pour vérifier l'url actuelle d'un site Web chaque seconde et changer les images des balises meta dans l'élément HTML en fonction d'une certaine chaîne de valeur. Mon code était parfaitement, mais je veux rendre mon code plus lisible 7 optimisé ... donc je veux transformer ce code en instruction switch à la place, mais je ne suis pas en mesure de le comprendre par moi-même à ce stade. Toute aide sera vraiment appréciée. Voici le code:
// Variable declarations
var imgOgSrc = $('meta[property="og:image"]');
var twitterImgSrc = $('meta[name="twitter:image:src"]');
var currentUrl;
// Checks for current url & changes meta tags depending on slug value
function getCurrentUrl(){
currentUrl = window.location.href;
if(currentUrl.toLowerCase().indexOf('python') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else if (currentUrl.toLowerCase().indexOf('java') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else if (currentUrl.toLowerCase().indexOf('php') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
}
else {
imgOgSrc.attr('content', currentUrl);
twitterImgSrc.attr('content', currentUrl);
}
}
4 Réponses :
Comme toutes les conditions if ont le même code, vous pouvez utiliser some comme celui-ci.
function getCurrentUrl() {
currentUrl = window.location.href;
const customUrlNeeded = ['python', 'java', 'php'].some(a => currentUrl.toLowerCase().includes(a))
if (customUrlNeeded) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else {
imgOgSrc.attr('content', currentUrl);
twitterImgSrc.attr('content', currentUrl);
}
}
Essayez ceci:
var currentUrl;
function getCurrentUrl() {
currentUrl = window.location.href.toLowerCase();
var langType = function(type) {
return currentUrl.indexOf(type) > -1;
}
switch (true) {
case langType('python'):
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
break;
case langType('java'):
// ...
break;
case langType('php'):
// ...
break;
default:
// ...
break;
}
}
ouais, cela fonctionnerait, mais ce n'est pas la meilleure solution.
Pas le meilleur, ouais, j'irais personnellement avec la solution de Taki moi-même. J'essayais juste de s'en tenir au choix d'OP d'utiliser switch .
au lieu de switch / case , vous pouvez stocker les images dans un objet, voir si currentUrl a le mot-clé, l'extraire puis l'utiliser pour obtenir les valeurs de cet objet:
// Variable declarations
var imgOgSrc = $('meta[property="og:image"]');
var twitterImgSrc = $('meta[name="twitter:image:src"]');
var currentUrl;
function getCurrentUrl(){
currentUrl = window.location.href.toLowerCase();
const obj = {
python : {
imgOgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg',
twitterImgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg'
},
java : {
imgOgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg',
twitterImgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg'
},
php : {
imgOgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg',
twitterImgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg'
}
}
const word = currentUrl.match(/php | java | python /gi)[0];
if(word){
imgOgSrc.attr('content', obj[word].imgOgSrc);
twitterImgSrc.attr('content', obj[word].twitterImgSrc);
}
else {
imgOgSrc.attr('content', currentUrl);
twitterImgSrc.attr('content', currentUrl);
}
}
Vous pouvez prendre un objet pour python , java et php avec imgOgSrc et twitterImgSrc properties amd utilise une propriété null pour ne pas correspondre à l'URL. function getTarget(url) {
const targets = {
python: {
imgOgSrc: 'data1',
twitterImgSrc: 'data2'
},
java: {
imgOgSrc: 'data3',
twitterImgSrc: 'data4'
},
php: {
imgOgSrc: 'data5',
twitterImgSrc: 'data6'
},
null: { // default values
imgOgSrc: 'data7',
twitterImgSrc: 'data8'
}
};
return targets[url.toLowerCase().match(new RegExp(Object.keys(targets).join('|')))];
}
console.log(getTarget('blablajavabla'));
console.log(getTarget('blablabla'));
où est la différence dans les parties alors?
Pour votre cas d'utilisation, les instructions if seraient la voie à suivre. Découvrez cette réponse qui a fait des tests de vitesse: stackoverflow.com/a/12259830/3684265
n'a aucun sens d'utiliser switch lorsque vous ne recherchez pas des correspondances exactes.
J'ai peur de ne pas comprendre Nina. Pouvez-vous élaborer un peu plus? @ imvain2 merci! Je vais y jeter un œil.
@epascarello Je vois, alors vous suggérez que je laisse mon code tel qu'il est?
@ManuelAbascal, Nina dit que les URL sont toutes les mêmes dans votre contenu attr pour les instructions if. Donc, si ce n'était pas une faute de frappe, vous n'avez besoin que d'un if et d'un else.
Je ferais correspondre l'url différemment et je combinerais les ifs puisque c'est le même contenu dans chacun.
Oh désolé, je ne me suis pas bien expliqué. L'image changera également en fonction de la chaîne. Bref, j'ai eu la réponse que je cherchais. Merci à tout le monde! Vous êtes top les gars!