Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Meteor JS, how to control Javascript load order in relation to DOM load order? For animations

I've got a template that I downloaded:

http://halibegic.com/projects/merlin/

I want to use it in Meteor and I'm having major issues with

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

at the bottom on line 444 not loading in the right order. When the page loads, none of the 4 functions specified in this js file work.

initNavbar(); initPortfolio(); initAnimations(); initTwitterFeed();

I have all the css, fonts, images, and js files in my public folder and they are all correctly referenced in the HTML. They are not in the lib directory which loads before everything else.

I think it's because the script is somehow loading before the DOM is loaded, so it has no DOM to apply things to.

Things I've tried:

  • When I change the name of script.js to main.js and change line 444 to <script src="assets/js/main.js"></script> the animations still don't work.

  • When I add this into the script file it still doesn't load correctly:

    $(document).ready(function () { initNavbar(); initPortfolio(); initAnimations(); initTwitterFeed(); });

  • I can do

    Template.layout.rendered/created = function () { add in all the function code and call them here }

    but this seems like an uncredibly, INCREDIBLY messy and inefficient way to do this. I need to specify the load order of individual files, not code. I have around five .js files in this template and I don't want to have to cut out their code and paste it all into one Template.layout.rendered/created function.

like image 480
fuzzybabybunny Avatar asked Dec 26 '22 09:12

fuzzybabybunny


1 Answers

All you need to do is to load the javascript after the template is rendered.

Template.yourLayout.created = function() {
  $('head').append('<script type="text/javascript" src="assets/js/script.js">');
}

If you have scripts loaded in $(window).load() or $(document).ready(), remember to get that out as well. You could run them in the promise of $getScript as well. This is your case:

$.getScript('assets/js/script.js', function() {
      initNavbar();
      initPortfolio();
      initAnimations();
      initTwitterFeed();
      $(".loader .fading-line").fadeOut();
      $(".loader").fadeOut("slow");
});
like image 193
Harry Ng Avatar answered Dec 28 '22 05:12

Harry Ng