jQuery - run code after scripts are loaded

11,929

Solution 1

Try calling it after the page loads

$(document).ready(function() {
  $(function(){
      $('.scroll-pane').load().jScrollPane();
  });
  function updateCSS() {
    numOfPics = $('#gallery-wraper img').size();
    widthOfAll = 0;
    $('#gallery-wraper img').each(function() {
        imgWidth = $(this).width() + 20;
        widthOfAll += imgWidth;
    }); // end of each
    $("#gallery-container").load().css("width",widthOfAll);

    galleryPosition = $(window).height() / 2 - 250;
    $("#gallery").css("margin-top", galleryPosition);
  }

  setTimeout('updateCSS()',100);
});// end of document.ready()

Solution 2

I am not sure if this is your issue or not, but try the $(window).load event instead of $(document).ready. $(window).load executes after all libraries, images, frames, ect have loaded instead of after your HTML code loading (as your libraries and images may still be loading).

http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/

Share:
11,929
smogg
Author by

smogg

Updated on August 22, 2022

Comments

  • smogg
    smogg almost 2 years

    In my header I load scripts (I keep this scripts on my server, original links are added here just for you):

    <script src="http://jscrollpane.kelvinluck.com/script/jquery.mousewheel.js"></script>
    <script src="http://jscrollpane.kelvinluck.com/script/mwheelIntent.js"></script>
    <script src="http://jscrollpane.kelvinluck.com/script/jquery.jscrollpane.min.js">
    

    Then on my footer I'm executing some code:

    $(document).ready(function() {
                $(function(){
                    $('.scroll-pane').load().jScrollPane();
                });
                numOfPics = $('#gallery-wraper img').size();
                widthOfAll = 0;
                $('#gallery-wraper img').each(function() {
                    imgWidth = $(this).width() + 20;
                    widthOfAll += imgWidth;
                }); // end of each
                $("#gallery-container").load().css("width",widthOfAll);
    
                galleryPosition = $(window).height() / 2 - 250;
                $("#gallery").css("margin-top", galleryPosition);
    });// end of document.ready()
    

    I want it yo display my images horizontally and put it inside jScrollPane (http://jscrollpane.kelvinluck.com/) But it displays my images horizontally after refresh only (or even after a few page refreshes in chrome). It looks like it tries to execute my code before page content is generated (its a wordpress theme) or before scroll libraries are loaded. What is wrong with my logic here? I'm using document.ready() so why it acts this way?