Search code examples
javascriptjqueryajaxgetscript

$.getscript creates multiple calls when using swup library


For those unfamiliar, I am using a library called swup to create page transitions using CSS. Repo and info here: https://github.com/gmrchk/swup

This is essentially an alternative to ajax transitions that I felt was pretty interesting and easier for me to use on my portfolio site.

My issue is that I need to load my script file when new content is loaded via swup. I’m using jQuery currently to just load my script file. The $.getscript function is called using an event from swup, called 'swup:contentReplaced':

document.addEventListener('swup:contentReplaced', event => {
  $.getScript("/js/main.js");
});

The problem with this is that this creates some sort of error that doubles every call created by swup. So the next time the 'swup:contentReplaced' event occurs, the main.js file is called twice. Then 4 times. Then 8, and so on.

This of course destroys performance and pretty much makes the computer freeze. What is a better way of calling that js file when content is loaded via swup on the page?


Solution

  • Obviously your main.js change the content and thus re-advocate the event twice.

    One option is, add global field in html which is flagged as false, and dig into your main.js find the piece of code cause you trouble like,

    //In HTML
    <data style="display:none" id="flag" value="0" />
    
    //In main.js
    $('#flag').val("1");
    //...Part causes trouble
    $('#flag').val("0");
    
    //eventListener
    document.addEventListener('swup:contentReplaced', event => {
      if $('#flag').val() == "0"{
         $.getScript("/js/main.js");
      }
    });
    

    But that may not solve the problem as you may find some trouble of locating the problematic part (lets say).

    Then, a more convenient way is using once

    document.addEventListener('swup:contentReplaced', event => {
      $.getScript("/js/main.js");
    }, {once:true});
    

    and at the end of main.js, also add this line.

    And thus everytime you can only call the $.getScript("/js/main.js"); for one time, and just after you execute the main.js, you add back the event.