1

I don't want to call the JavaScript functions at the startup. The reason is simple, it will reduce the initial download size and the page will be appear faster. To do that I used the following code inside head section..

<script type="text/javascript">
 // Add a script element as a child of the body
 function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "deferredfunctions.js";
 document.body.appendChild(element);
 }

 // Check for browser support of event handling capability
 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;
</script>

But it did not work...please help me

curtisk
  • 18,798
  • 4
  • 50
  • 68
Sajib Shome
  • 11
  • 1
  • 2
  • Related: http://stackoverflow.com/questions/912711/jquery-to-load-javascript-file-dynamically – masoud Apr 11 '15 at 11:03

3 Answers3

4

Usually, it's better to put scripts in the end of your body, and call them immediately.

Scripts block loading of the page, so putting them at the end of body allows the page to load quickly, and the javascript will load with page already ready.

timw4mail
  • 1,466
  • 2
  • 11
  • 16
  • Some even suggest adding another `head` element after the `body` element and put scripts into the former. Is it good practice? – katspaugh Jul 07 '11 at 14:02
  • @katspaugh I would avoid adding a second head, since it is not standard, and has no benifit. – timw4mail Jul 07 '11 at 14:18
1

You can use <script defer> (defer attribute on HTML script tag).

Example:

<script src="link/to/yourfile.js" defer></script>

defer will download the file during HTML parsing and will only execute it after the parser has completed. defer scripts are also guaranteed to execute in the order that they appear in the document.

GibboK
  • 64,078
  • 128
  • 380
  • 620
1
document.head.appendChild(element)
Senad Meškin
  • 12,841
  • 4
  • 37
  • 53