Question

I have two JavaScript files:

  1. scripts.js - does all the onload setup work and attaches event handlers to controls
  2. map.js - defines a MAP widget

When the document loads, scripts.js initialises a MAP object by loading map.js and calling initMap:

/** ON DOCUMENT LOAD **/
$(document).ready(function() {

  $.getScript('lib/map.js', function() {
    /** Generate a new map **/
    MAP = initMap(10,mapDefault);
  });

There is a button that allows a user to regenerate the map, which also calls initMap. For example:

$('input#regenerateButton').click(function() {
  $.getScript('lib/map.js', function() {
    MAP = initMap($('input#mapSize').val(),mapDefault);
  });
});

Do I need to re-load the script map.js again, since it will likely have already been loaded at this point?

This question has been asked previously, however I don't believe the part about multiple calls to $.getScript was answered.

Was it helpful?

Solution

By default the $.getScript() function mangles the cache - meaning that each time it is executed the file will be fetched again. This is useful only if the js file is not a static js-file, i.e if it contains some server-side code (such as PHP) which customizes the data according to some other data available to the session.

If you have a static js file, which it appears that you have, you can disable this behaviour by doing

$.ajaxSetup({
  cache: true
});

(note though that this is global for all ajax calls).

You do not need to reload the script with another $.getScript() if your script is a static file. And if you do not try to reload it, there is no need to enable AJAX caching either.

There is one exception to not needing to reload the script even if it is static though: If the MAP script stores some information which is not reset when you do initMap. That would be bad design, but it could be the case in a script.

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