skip to Main Content

So basically I have a code that looks for divs and appends an iframe to them, but I made them as a start only with if statements, any idea how can I refactor them, tried a few else-if’s but they didn’t work. The code looks like this:

if ($('.similar-products')) {                                       
    $('.similarproducts').append(iframe_html);
} 

if ($('.partial--product')){
    $('.partial--product').append(iframe_html);
}

if ($('.product-page')){
    $('div.product-page').append(iframe_html);
}

if($('#section-product-page')){
   $('#section-product-page').append(iframe_html);
}
//needs fix
if($('.swatch-product-id-*')){
   $('.swatch-product-id-*').append(iframe_html);
}

if($('.product__tabs')){
   $('.product__tabs').append(iframe_html);
}
if($('.main-content-wrapper')){
   $('.main-content-wrapper').append(iframe_html);
}

if($('#shopify-section-product-description-bottom-template')){
   $('#shopify-section-product-description-bottom-template').append(iframe_html);
}
if($('.product-details-inline')){
   $('.product-details-inline').append(iframe_html);
}

if($('.social-footer')){
   $('.social-footer').prepend(iframe_html);
}
if($('.section-related-products')){
   $('.section-related-products').append(iframe_html);
}

if($('.product-details')){
   $('.product-details').append(iframe_html);
}

2

Answers


  1. You can use Switch case statement instead of if and else because in case of if else server will check each if and else condition, but in case of switch it will directly jump over the relevant case block. so it maximise the performance

    Login or Signup to reply.
  2. I presume you are using jQuery here. If that is the case, having if blocks is pointless. Because jQuery looks for the matching selectors and perform the tasks specified in the functions. If no elements are found for the given selectors, the routines will be ignored without errors. So, having something like

    if ($('.similar-products')) {                                       
        $('.similarproducts').append(iframe_html);
    }
    

    is nothing different from

    $('.similarproducts').append(iframe_html);
    

    Additionally, think about grouping the selectors, if the <iframe> that you are appending is the same for all. So it would be something like

    $('.similarproducts, .partial--product' /* Rest of the selectors */).append(iframe_html);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search