Question

I'm in charge of building my band's website and tumblr. I'm in the paper draft stage. Currently thinking how to handle scripts to optimize performance.

Basically, I'd need:

  1. jQuery: to manipulate DOM once it's ready as well as some interactivity.
  2. jPlayer with jPlayer's playlist plugin for an HTML5 music player with Flash fallback.
  3. A custom script to load data from the Songkick API (tour dates). It'd add tour show to the page. Should happen after the DOM is ready (Ajax request).
  4. A custom script to load songs from SoundCloud using their API. That should occur when a user is clicking in the play button from the music player (those are long tracks, loading them during page load is a bad practice).

SO, I'm thinking about how to structure all those scripts so that things occurs at the good time in the good order. I've been off the dev scene for some years but read a bit before posting. Saw that now the design pattern of JS tends to use a modular approaches. I've read a bit on the RequireJS website and might give it a try.

Well, my main question is, how should I structure my scripts so that it loads at the correct time with the best performance possible? Is RequireJS an option to solve such design patterns issues?

Sorry, it's not a syntax problem but more a thinking pre-coding problem. I'm just trying to think right before getting my hands dirty.

Regards, O.

Was it helpful?

Solution

I think you're at risk of premature optimization. I'd just load in scripts normally, and if you see performance problems, then you can bring in tools like Require.js. With just 4 scripts, I doubt you're going to have any problems.

That said, a few pointers for loading script:

  • Load the scripts at the bottom of the <body> (just before the </body> closing tag), not in the <head> - this way the loading of your page content won't be held up by your scripts.

  • Wrap your custom script in document.ready:

    $(document).ready(function() {
      // your code
    });
    

    this mean your script won't run until everything's been loaded, avoiding any problems with load order.

  • Use Google's CDN to load jQuery. It's fast, and (more importantly) a lot of sites use it, so it's likely to be already cached by the user:

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
    

    https://developers.google.com/speed/libraries/devguide

If you're still worried about the different ways to load scripts, this is the best resource I know of, with exhaustive Pro/Cons of each approach:

https://developer.mozilla.org/en-US/docs/XUL_School/Appendix_D:_Loading_Scripts

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top