0

I have a JS which works fine. I call it from my HTML page using the standard following metatag :

<script src="js/my_script.js"></script>

The fact is I would like my_script.js NOT to be called/load if the page is read from a Mozilla Firefox browser...

Is it possible to do that ? And if so, may I ask how ?

PS - I tried to condition the loading of my_script.js the following way, for example (it didn't work) :

<script>
    if($.browser.mozilla) { 
        jQuery.getScript("js/blank_script.js");
    } else {        
        jQuery.getScript("js/my_script.js");            
    }
</script>
j08691
  • 204,283
  • 31
  • 260
  • 272
TAQ
  • 1
  • 1
  • I think your `if` statement should work. But remember that `getScript()` is asynchronous, so anything that depends on the result should be in its callback function, not at top-level – Barmar May 04 '23 at 20:05
  • This thread may be helpful https://stackoverflow.com/questions/59905328/how-to-load-and-run-a-javascript-file-conditionally – Peterrabbit May 04 '23 at 20:07
  • You could also make the script detect the browser and not do anything when the browser context is not what you expect. Or, even better, make the script work in *any* browser context, because denying functionality to people using a browser you don't like is weird. – Pointy May 04 '23 at 20:12
  • Thanks, Barmar. I understand what you mean, Pointy. The fact is my_script.js contains some code allowing gapless loops when playing mp3/ogg using the – TAQ May 04 '23 at 20:42
  • `jQuery.browser` has been deprecated for quite a while and removed entirely in the last couple of versions: https://api.jquery.com/jquery.browser/. The authors note: “This API has been removed in jQuery 1.9; please rely on feature detection instead.“ If you’re dead-set on ignoring Firefox, you might check a Firefox-specific property on the window object like `window.mozInnerScreenX != null` to determine whether you’re working with Firefox or not. – Mikol Graves May 05 '23 at 01:20

1 Answers1

0

You can create a new script element, set it's src attribute and append it to the DOM.

const script = document.createElement('script');
if($.browser.mozilla) {
  script.src = 'js/blank_script.js';
} else {
  script.src = 'js/my_script.js'
}
document.body.appendChild(script);

or you could replace the if statement with a ternary operator:

const script = document.createElement('script');
script.src = $.browser.mozilla ? 'js/blank_script.js' : 'js/my_script.js';
document.body.appendChild(script);
  • Thank you very much for the information. Sadly, when I do that, my_script.js doesn't load on any browser. I'll try to work on that, though... – TAQ May 04 '23 at 20:45
  • Try: `script.src = window.mozInnerScreenX != null ? 'js/blank_script.js' : 'js/my_script.js';` – Mikol Graves May 05 '23 at 01:21