1

The idea is after the ready() function completes, lets say user clicks a button. Then the java script code behind it will run ajax to retrieve some java script code snippets (as text), then it executes the code just downloaded.

Is it possible? Any frameworks can do it?

2 Answers2

0

You don't even need ajax to do it. You can simply create a new script element with the src attribute set to your JS file and insert it in the DOM (usually in the head element).

var script = document.createElement('script');
script.setAttribute('src', 'myfile.js');
document.head.appendChild(script);
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • Hi Tibos, I haven't tried the code above yet. Will the download code snippets run after DOM is loaded? I see someone use eval() to execute javascript code at runtime, but not reliable on Chrome: (please see the last comment by user1251840, http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously). Do you know any framework can do it better? Thanks. – user3300681 Feb 12 '14 at 17:48
  • The code inside the snippets is executed as soon as it is downloaded. However, if in those code snippets you set a variable for example, that variable will not be available in the calling script. – Tibos Feb 12 '14 at 18:13
0

Thanks Tibos for providing me the clues. I used your code to search for what I want, and here it is.

Jan Wolter described his solutions to dynamically load and execute the javascript at run time. (http://unixpapa.com/js/dyna.html). It seems that the unstable-ness of dynamic JS loading is related to the JS code file size. If JS code file is big, different browsers may behave differently. Jan provided a way to avoid it. Thanks again.