Allan Araújo Allan Araújo - 1 year ago 53
Javascript Question

jQuery sending query strings on every script embebbeding

i'm using MaterializeCSS, AngularJS and jQuery to build a simple webapp.
Since i'm using Materialize, and due to the why i designed it, i need to initialize the sidebar button in every AngularJS view with jQuery.

If i copy this on every view, it works fine:

menuWidth: 150

however, if i create a new js file called sidenav.js:

<script src='/js/sidenav.js'></script>

for some reason, jQuery(or maybe Angular, but the XHR is initiated by jQuery) sends an XHR with a query string to load this script, thus invalidating the cache and causing an 'lag' due to latency. While after some usage all views are cached, the script keeps being reloaded because of the query string:

[Thu Jul 21 16:39:31 2016] [200]: /js/sidenav.js?_=1469129949496
[Thu Jul 21 16:39:37 2016] [200]: /js/sidenav.js?_=1469129949497
[Thu Jul 21 16:39:42 2016] [200]: /js/sidenav.js?_=1469129949498
[Thu Jul 21 16:39:42 2016] [200]: /js/sidenav.js?_=1469129949499
[Thu Jul 21 16:39:47 2016] [200]: /js/sidenav.js?_=1469129949500
[Thu Jul 21 16:39:51 2016] [200]: /js/sidenav.js?_=1469129949501

How can i stop jQuery or Angular from putting a query string on it, or other method to cache it?


Answer Source

jQuery's $.ajax() function has a cache parameter in its settings object. By default, cache is true for most data types, except for for jsonp and script where it defaults to false. This causes the random _ query parameter.

If you have access to the specific $.ajax() call that is downloading this script, you can fix this by adding cache: true to the settings object for that call.

Otherwise, you can use $.ajaxSetup() with a cache: true value. This should do the same thing, unless the specific $.ajax() call has cache: false in it, or if some other call to $.ajaxSetup() overrides this value. Also, if some other code relies on the default cache value, this will affect that code as well.

It's also possible that the script is being loaded with a $.getScript() call, which does not take a settings object and has no way to override the cache setting directly. If this is the case, you can either change $.getScript() to the equivalent $.ajax() call and add the cache: true setting there, or you can use $.ajaxSetup().

See the documentation for $.ajax(), $.getScript(), and $.ajaxSetup() for more information.