0

Possible Duplicate:
When should I use Inline vs. External Javascript?

I have some javascript variables that I use in my javascript (ie. external javascript files)

This javascript variables is page specific and varies per page and user.

Is it better to have these in any other javascript file meaning an extra http request or including it within the html content of the page, bloating the page.

I like separation but want to do all to maximize performance, so either increasing html page size or extra http request.

I ask this question in terms of performance/optimization.

Opinions on this please?

Community
  • 1
  • 1
amateur
  • 43,371
  • 65
  • 192
  • 320

3 Answers3

1

You could do this a couple different ways. One way would be to include the data in an object included with your main script and have another object per page. Something like

var data = {
 "page1": {
  "title": "blah"
 },
 "page2": {
  "title": "different blah",
  "users": [...]
 }
}

Alternatively you could do a config loader. in each html page include

<script src="loader.js" type="text/javascript"></script>

Which would contain something like this

// if the page was blog.html page would equal blog
var page = window.location.href.match(/\/(\w+).html/)[1];
var s = document.createElement("script");
s.src = "/path/to/javascript/" + page + ".js";
s.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(s);

This could load any additional data the specific page needs and if done in the very beginning would work along side with mostly libraries equivalent of onReady like

jQuery(function() {
 doStuff();
})

For this method to work you would just need to ensure the data in each file is uniform in the data is contains.

var pageData = { ... };

These two methods should give you a bit to think about in coming up with a solution.

Morgan ARR Allen
  • 10,556
  • 3
  • 35
  • 33
0

you can have 2 versions of your app dev and release.
In your dev version, you don't really care about the number of scripts, whereas, your release version should be optimized by merging all the scripts in one, minifying it and gzipping it.

gion_13
  • 41,171
  • 10
  • 96
  • 108
0

If the data varies by user and by page, then they cannot be cached effectively by the browser, so putting them in an external file will not benefit from browser caching and in fact, you'll explicitly have to prevent the file from getting cached. I'd suggest you put it in the actual web page. If you can, put it after the web page HTML so that can render first.

jfriend00
  • 683,504
  • 96
  • 985
  • 979