Page-specific script in Bootstrap Studio

(This problem is specific to Bootstrap Studio)

I need to include a piece of JS that is specific to just one page.

  • I can’t put it in a JS file since it is specific to one page and BSS apparently has no option to link JS files to individual pages. It always imports all JS files in all pages (which itself is a serious limitation in my opinion).
  • I can’t put it in a Custom Code block in the page because it uses jQuery, which is loaded AFTER the entire page content (including jQuery.js) by BSS, thus I see $ is not defined error when my script runs.

What is my way out?


Solution 1:

You have :

  • 1) to wait jQuery is loaded, you can do this with such code :

    $( document ).ready(function() {
      // Handler for .ready() called.
      if (window.location.pathname == '/mypage.php') {
        // execute my custom code
      }
    });
    

or

    var waitForJQuery = setInterval(function () {
    if (typeof $ != 'undefined') {    
        // place your code here.
        if (window.location.pathname == '/mypage.php') {
          // execute my custom code
        }

       clearInterval(waitForJQuery);
        }
    }, 50);
  • 2) if you want to execute your code only on a custom page, you can check on which page you are, and if you are on the good page, you execute your custom code

    if (window.location.pathname == '/mypage.php') {
      // execute my custom code
    }
    

    See more possibilities here : Best way to execute js only on specific page