How to add JavaScript file dynamically from JavaScript on client Side

We can add java script file on client side under head tag by JavaScript dynamically. Below is working code

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", filename);
                fileref.setAttribute("ID", "jsScript");
                document.getElementsByTagName("head")[0].appendChild(fileref);

Let’s Understand the above code We have to put script under head tag in below format

<script src="http://code.jquery.com/jquery-2.0.0.js" type="text/javascript"></script>


So for doing this have to define filename = which can be file name and absolute and relative JS file path name.Now we have to create script element which can be done using document.createElement(‘script’) method. And for adding attribute can be used setAttribute method.


Note: Here I have also set ID property fileref.setAttribute(“ID”, “jsScript”); which is optional. It will be helpfull when you want to check whether already page contains script with this ID or not.

Below code is used for check whether already have included Js file if yes then don’t include So It can be used to Check to see if script is present before adding one.

        var jsSelector = document.getElementById("jsScript");

        if (!jsSelector) {

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
            fileref.setAttribute("ID", "jsScript");
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
 

Page Keyword: How to check js file already loaded or not, add js file dynamically, add java script file by java script

Advertisements

One thought on “How to add JavaScript file dynamically from JavaScript on client Side

  1. Pingback: include js file on other js file just like php: main_functions.js (part 5) | Web and Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s