{{announcement.body}}
{{announcement.title}}

Avoid Loading JS Files Multiple Times for Component Based Web Frameworks

DZone 's Guide to

Avoid Loading JS Files Multiple Times for Component Based Web Frameworks

Get more efficient with loading files in JavaScript.

· Web Dev Zone ·
Free Resource

medical-book-with-tabs

In this article I will talk about how to avoid loading the same JavaScript files multiple times for component-based web frameworks like JSF, Wicket, etc. For example, when you have a JSF composite component and it contains a link to an external JS file, including this composite component multiple times to XHTML will lead to multiple links to same external JS file.

Including the same JS for multiple times in an HTML document can be the reason for weird JS behaviors like running the same code multiple times.

You may also like: JavaServer Faces 2.0.

Solution

To overcome this issue, the solution explained below can be added into component's front end code. (For JSF, it is XHTML of the composite component.)

<script>

  try{

    isComponentResourcesAlreadyIncluded; //this variable is flag of whether resources already loaded or not.

  }
  catch(e) {

    if(e.name == "ReferenceError") {

      isComponentResourcesAlreadyIncluded = true;

      //assuming jquery is included.

      //load JS files as per your needs.
      $.ajax({
        async: false,
        url: "/static/js/a.js",
        dataType: "script"
      });

      $.ajax({
        async: false,
        url: "/static/js/b.js",
        dataType: "script",
        cache: true
      });

      $.ajax({
        async: false,
        url: "/static/js/c.js",
        dataType: "script",
        cache: true
      });

      $.ajax({
        async: false,
        url: "/static/js/d.js",
        dataType: "script"
      });

    }
  }

</script>


How It Works

(Assuming a page contains multiple composite components.)

JavaScript's engine executes instructions one-by-one. First, it comes across with the first composite component's JS block (described above) and executes it. It then throws a ReferenceError, since there is no  isComponentResourcesAlreadyIncluded.

Then, it executes the catch block, sets isComponentResourcesAlreadyIncluded to true, and loads defined JS files. After these executions and maybe executing some other codes, if the script comes across the  same composite component's JS block (described above) and executes it. Since isComponentResourcesAlreadyIncluded is defined in first run, the catch block won't be executed. No more multiple load of same JS files!


Further Reading

Topics:
javascript ,jsf ,jquery ,web dev ,ajax ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}