Reputation: 34152
I want to load my javascript files after the page is loaded and make sure that they are being cached.
This question has been asked and answered a lot but they all suggest loading it with jQuery ($.getScript
) while one of the files I want to load is the jQuery itself and I can not use jQuery. there are some options like:
(function(){
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = false; //as I'm going to execute some functions
//after this I want to make sure that the
//script is fully loaded
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})();
but I'm not sure if they are cached or not. and Is there a way to fire an event when dynamically loading script is done?
Upvotes: 0
Views: 1371
Reputation: 116100
You can easily check if they are cached by loading your page for a second time with the network tab of the developer tools of your browser opened. You can tell by the way the scripts are loaded whether the file is cached or not.
They should be, by the way. You're basically inserting a script tag through JavaScript, after which the script is loaded as it would be if the tag was already in the page.
If you make it load asynchronously, you can attach an onload
event to a script tag, which will fire as soon as the script is loaded. This should work in any modern browser, including IE9+ in standard mode. If you need support for IE8, you will have to do some extra work, which is what $.getScript()
also does. An in-depth discussion of that jQuery functionality, with alternative code snippets can be found in the question 'onload' handler for script tag in Internet Explorer.
Upvotes: 2