Best way for including javascript/jQuery OnLoad in EVERY page on my site Currently, in my theme.info file I am including 2 scripts:

scripts[] = js/backstretch.js
scripts[] = js/scripts.js


Backstretch is a jQuery plugin that allows for an expanding background image to cover your entire page.

I am currently using this code to autoload the JS:

(function ($) {

    var bgs=["bg1.jpg", "bg2.jpg"];
    var bgr=Math.floor(bgs.length * Math.random());
    $.backstretch(bgs[bgr], { speed: 1000 });

})(jQuery);


Two issues:


Sometimes it doesn't load the backstretch.js properly which may have something to do with my current OnLoad function in scripts.js. It loads the image but not maximum width/height of the browser initially.
For some reason, it doesn't work past 1 level in the site (although the JS seems to load when I check the site (could it be that the location of images is not relative of the JS file?) e.g.,:



  Works: site.com, site.com/page
  
  Doesn't Work: site.com/dir/page, site.com/dir/dir/page


I was wondering in my scripts file what would be the best OnPageLoad (or Preload?) function would be best to use?

Many thanks in advance.
Please read Managing JavaScript in Drupal, specifically the section on Behaviors. You'll need to do something like this:

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      var bgs=["bg1.jpg", "bg2.jpg"];
      var bgr=Math.floor(bgs.length * Math.random());
      $.backstretch(bgs[bgr], { speed: 1000 });
    }
  };

})(jQuery);