Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery adding querystring to script load?

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.

like image 763
Zarigani Avatar asked Apr 13 '26 11:04

Zarigani


1 Answers

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(){

  }
});
like image 60
MrCode Avatar answered Apr 16 '26 00:04

MrCode