1

Is it possible to load a javascript file in a browser (e.g. from some javascript code) without the loaded code being executed?

The goal would be to just download the javascript file to ensure that the browser's cache has the current version of a javascript file.


(Here's a little more background about where the question comes from)

We have a web application which contains lots of javascript files, which are included on different pages of the application. After a new version of the web application is deployed we sometimes have the problem that some user's browser uses old versions of the javascript files (from the browsers cache).

I was thinking about some ways to solve this problem, and one idea was the following:

  • on the login page, we can detect when a user uses the current version of the app for the first time
  • if that is the case, load a page in a hidden iframe, which (pre-)loads all javascript files with a unique query-string parameter (e.g. <script scr="file1.js?v=123" ...>), to ensure that the browser's cache contains the current version of each file

One possible problem of that approach would be javascript errors due to the js-files being executed after they are loaded. That's what lead to this question.

M4N
  • 94,805
  • 45
  • 217
  • 260
  • This question is answered please refer http://stackoverflow.com/questions/8843132/what-are-the-ways-to-load-javascript-or-css-without-executing-them link . – Novice Aug 13 '15 at 21:15
  • you can load up libs angular jQuery bootstrap and load your main executables js later when you get to that page. Also you can define js in one and your document.ready() + self executing scripts goes in another only that will execte when you reach to your intended page – joyBlanks Aug 13 '15 at 21:17
  • Append a parameter to the URL of your scripts, and update that when you build a new version of your application. That way you can be sure that the browser will load a new, uncached version. – Anthony Grist Aug 13 '15 at 21:19
  • @AnthonyGrist: yes that's another option, but requires editing lots of files (unless it can be automated), which is why I was looking for other solutions. – M4N Aug 13 '15 at 21:24

2 Answers2

1

This can load scripts into new elements that are not part of your HTML.

var scripts = ['script1.js', 'script2.js', ...];

for (var i in scripts) {
  var s = document.createElement('script');
  s.src = scripts[i];
}
blzn
  • 342
  • 1
  • 3
  • 15
  • But wouldn't this execute the scripts? – M4N Aug 13 '15 at 21:18
  • They execute only after appending them to the document. – blzn Aug 13 '15 at 21:36
  • 4
    I tried that in chrome: it only downloads the scripts when the script elements are added to the document. And at that time, they are also being executed. – M4N Aug 13 '15 at 21:52
-1

You can put the script in a function, that you can call later when needed.

Milkmannetje
  • 1,152
  • 1
  • 10
  • 35