3

Adding this js to my page:

$("#divExample").append("<script type='text\/javascript' src='\/scripts\/test_code.js'><\/script>");

Causes a request to:

http://.../scripts/test_code.js?_=1395691742415

I need to eliminate the query string as it is preventing the js file from being cached. My best guess is that this is in some way connected to jQuery ajax, which appends the same style of querystring when doing certain types of call (e.g. jsonp).

Background on why I'm doing this: I need to push off the script load (which is actually a part of a larger js block) until after the page ready event has completed. The above is just a cut down sample which shows the same symptoms.

Currently using jQuery 1.8.3 but I really hope the answer doesn't include upgrading since that will mess with dependencies.

1 Answer 1

5

Set the jQuery cache global to true to prevent this.

$.ajaxSetup({
    cache: true
});

Even though this appears to be config just for ajax, it affects <script> tags like you're using.

If you don't want to apply the global to all ajax requests, you can use plain Javascript (no jQuery) to do it:

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'test.js';
document.getElementById("divExample").appendChild(s);

The third option is you can use $.ajax to import the script like so:

$.ajax({
  url : 'test.js',
  type : 'script',
  cache : true,
  success : function(){

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

3 Comments

Presumably this will also affect legitimate ajax calls on the page though?
Yes it will. See my edit, either use plain JS or in your ajax calls you can individually disable caching $.ajax({ ... , cache : false }).
Great, thank you. I've just realised that the global cache option won't affect standard json ajax so I might use it after all but the other options both look very useful.

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.