0

I am currently working on a website that includes several very large Javascript files. These files are causing the load time of the page to become very slow.

The output of the javascript files are initially hidden to the user behind several jquery tabs. I was wondering if it is possible to load the files only when the user clicks on those specific tabs so that the initial load time of the website wouldn't be slow?

eric212
  • 43
  • 2
  • 10

2 Answers2

3

Javascript files can be loaded dynamically upon demand when you need them.

This will be an asynchronous operation so you will start the loading process and then some time later the script will be loaded and available to you.

In jQuery, you can use $.getScript().

Example:

$.getScript("test.js", function() {
    // script is loaded now
    // code that uses this script can go here
});

FYI, there are other techniques for improving the load time of your site. For example, you can put all non-essential scripts (those not involved in the initial display of your page) at the very end of the <body>, right before the </body> tag. This will allow your page to display without waiting for those scripts to load.

Scripts can also be marked async and defer so that other aspects of page loading will NOT wait for them to load.

Other useful references on this topic:

Script Tag - async & defer

Deferred scripts and DOM

load and execute order of scripts

improving website performance by dynamically loading javascript?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Yes you can do this. See http://community.sitepoint.com/t/dynamically-loading-js-script/40207/15

You will probably have to do some string concatenation in the filename when writing out the src attribute so its loads the different file you require

JaranF
  • 71
  • 3