I have the below code which is working as expected is there any way i can reduce the number of lines or functionality so that it can be more modular.
The concerns are I'm calling the exponea track event twice I was wondering is there any way I can construct it once and pass parameters to that based on if else condition. I'm learning javascript so looking for any code optimization
window.onload = function () {
var categorycollection = JSON.parse(document.querySelector('.pipa').getAttribute('data-globaltargeting'));
var isprofessional = (categorycollection['Type'] == 'PatientPlusArticle') ? 'Yes' : 'No';
if (categorycollection['Type'] == 'PatientPlusArticle' ||
categorycollection['Type'] == 'MedicineLeaflet' ||
categorycollection['Type'] == 'PatientInformationLeaflet') {
exponea.track('page_visit', {
"referrer": document.referrer,
"path": window.location.pathname,
"category name": document.querySelectorAll('.breadcrumb-item')[1].querySelector('span').innerText,
"Isprofessional": isprofessional
});
}
else {
exponea.track('page_visit', {
"referrer": document.referrer
, "path": window.location.pathname
});
}
}
The conditional operator can assign the additional properties when needed - otherwise, use the empty object. Merge the result into the call to .track. You can also use .includes instead of extracting the Type so many times.
const { Type } = JSON.parse(document.querySelector('.pipa').getAttribute('data-globaltargeting'));
const additionalObj = ['PatientPlusArticle', 'MedicineLeaflet', 'PatientInformationLeaflet'].includes(Type)
? {
"category name": document.querySelectorAll('.breadcrumb-item')[1].querySelector('span').innerText,
Isprofessional: Type == 'PatientPlusArticle' ? 'Yes' : 'No'
} : {};
exponea.track('page_visit', {
referrer: document.referrer,
path: window.location.pathname,
...additionalObj
});
The selectors and child indicies are a bit of a code smell, though - I don't know the broader context, but that part probably deserves refactoring too. Otherwise, it'd be very easy for a simple change to the HTML to break everything.