Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load js when visible

I have a phtml page that has separate tabs

<div id="maintabs">
    <ul id='mainTabNav'>
        <li><a href="#maintabs-1">Tab 1</a></li>
        <li><a href="#maintabs-2">Tab 2</a></li>
    </ul>
    <div id="maintabs-1">
        <p><?php require_once VIEW_DIR."somewhere/tab1.phtml"; ?></p>
    </div>
    <div id="maintabs-2">
        <p><?php require_once VIEW_DIR."somewhere/tab2.phtml"; ?></p>
    </div>
</div>

Each tab/page has a header with a js source specific to the page like this

<script src="js/tab<num>.js"></script>

On the page load though each javascript file is loading. Is there a way to only load the js for the tab currently open? When a new tab opens then the js reloads with just the js for the current tab?

like image 554
depperm Avatar asked Sep 07 '26 04:09

depperm


1 Answers

You could keep click events on each of the main tabs that would dynamically load the appropriate javascript using something like jQuery.getScript().

$('div[id^="#maintabs"]').click(function(e){
  var tabno = $( this ).index();
  $.getScript("js/tab"+tabno);
});

The pitfall I'd imagine with this is that you seem to want to have all the previous javascript to be washed away once the latest JS file was loaded. I'm not sure if that's doable or if you'll have side effects from it.

Also this could totally be done with vanilla JS but well, time savings.

like image 182
Camilo Payan Avatar answered Sep 09 '26 19:09

Camilo Payan