Reputation: 229
Im trying to add some JavaScript to my website dynamically using this syntax:
$('head').append('<script type="text/javascript" src="js/myjavascript.js"><\/script>');
It loads, but when I observe throw the chrome network tab, I observe that the request it's holding a ?
like for example in this case, the request url for the JavaScript is:
http://mywebsite/js/myjavascript.js?_=1406082938676
I don't know what that final number is, didnt set it anywhere, but I imagine that with that number the browser is not able to cache my JavaScripts.
Anyone know how to add JavaScript dynamically without that flag?
Upvotes: 1
Views: 1015
Reputation: 1312
The final number is random number for loading script not from cache. Here's how it works:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/' + pagename + '.js?rand=' + Math.random();
document.getElementById('dynamicScripts').appendChild(script);
Where:
dynamicScripts is DOM element. It can be 'body'
you can use ajaxPrefilter for a loading without this key
Upvotes: 3
Reputation: 3754
jQuery by default appends the underscore parameter with the current timestamp value. This is to avoid the script to be cached (i.e. each time the append is executed, the browser will download the script).
You can change this behavior and allow cache. From this answer, you can add an ajaxPrefilter
like this:
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.dataType == 'script' || originalOptions.dataType == 'script' ) {
options.cache = true;
}
});
Upvotes: 5