2

What is the best way to import and use JavaScript code in HTML pages? I am considering two options:

  • Have single <script> tag with all.js file that is imported to HTML files, that uses selected JavaScript methods.
  • Define separate <script> tag in each HTML file separately.

What is the best design option here?

2
  • 1
    Well minify javascript and use it accordingly it will help :) Commented Jun 27, 2012 at 8:54
  • Work out how you would do this with HTML and you have the answer. It is the same for JSP, PHP, ASP.. Commented Jun 27, 2012 at 8:56

4 Answers 4

4

Lukasz, this innocent question is a big topic. To get started with JavaScript performance and maintainability in a nice place, follow Steve Souders' writings on this.

And use JSHint. That's much easier if your code is in a JavaScript-only file. To find out about other good practices, read idiomatic.js.

Sign up to request clarification or add additional context in comments.

Comments

1

A single minified file is the most performant - less requests and smaller download. But not one global js for everywhere, that would be a pain to debug/develop.

Use a cdn for libraries as probably cached in browser.

Comments

0

IMO I will have separate tags for separate javascript snippets/plugins, it will make my javascript code easier to maintain. I can remove the plugin/add the plugin without disturbing the other javascript snippets.

But for performance issue, modern browsers will run 6 consecutive threads to download the resources, so it will be good idea to profile the loading times of the site/web app. You can use tools like Firebug/yslow to profile http requests being sent from the html page.

Personally I use template engines like Sitemesh and create templates for jsps for different parts of the application.

And for javascript I mainly use JQuery and a lot of plugins.

Comments

0

Minify js is a good and acceptable way. it also helps to build js files on the server side at run time. This is a big topic. Here are some good advices from yahoo. I use these as my guidlines. Also read on the topic js minify http://developer.yahoo.com/performance/rules.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.