Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically load javascript?

I use a lot of script in an application, some of them are not required to load the application, I want to load them just before their use if possible, knowing that my application is coded in ExtJS, and uses many ajax calls

like image 881
cranberies Avatar asked Feb 20 '11 15:02

cranberies


People also ask

What is dynamic loading in JavaScript?

To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes. Append the script element to the body. Check if the file loaded or not in the load event.

What is Dynamic script in JavaScript?

Both AJAX and dynamic JavaScript refer to ways of using JavaScript. Both are methods of creating an action on a web page without loading that entire page in the browser. AJAX and dynamic JavaScript can make a website faster and more responsive to the user.

How do you load a script in JavaScript?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.


3 Answers

You could look at using LABjs which is a script loader.

Old and busted:

<script src="framework.js"></script>
<script src="plugin.framework.js"></script>
<script src="myplugin.framework.js"></script>
<script src="init.js"></script>

New hotness:

<script>
   $LAB
   .script("framework.js").wait()
   .script("plugin.framework.js")
   .script("myplugin.framework.js").wait()
   .script("init.js").wait();
</script>

Update: If you want to load jQuery you could do something like this from this blog post.

<script type="text/javascript" src="LAB.js">
if (typeof window.jQuery === "undefined") {
    $LAB.script("/local/jquery-1.4.min.js");
}
like image 127
Mark Coleman Avatar answered Oct 05 '22 05:10

Mark Coleman


You can load an external file using javascript only when/where you need it:

function LoadJs(url){
  var js = document.createElement('script');

  js.type = "text/javascript";
  js.src = url;

  document.body.appendChild(js);

}

LoadJs("/path/to/your/file.js");
like image 23
brendan Avatar answered Oct 05 '22 03:10

brendan


Here's a great post on the topic with a proposed solution you might want to check out: http://www.nczonline.net/blog/2011/02/14/separating-javascript-download-and-execution/

like image 26
Gobhi Avatar answered Oct 05 '22 04:10

Gobhi