3

I would like to know how to import a .js file inside another .js file just like how we import css file inside another css file

all.css file goes like this.....

     @import "simple1.css";
     @import "simple2.css";
     @import "simple3.css";
     @import "simple4.css";

same way i wanna import js/jquery-1.7.1.min.js in my custom.js file

custom.js file goes like this

    $(document).ready(function(){

    $("#AddImage").html("<img src='"+clientID+".jpg'/>");

    });

i don't want to include js/jquery-1.7.1.min.js like

      <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>

i want to include it in my custom.js file.

Please help! Thanks in advance!!!

Christina
  • 199
  • 2
  • 12

3 Answers3

5

You can create function like below.

function importJs(url)
{
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    head.appendChild(script);
}

to run the code, see example below

importJs("myScript.js");

Now you can use importJs() in your any js. Which you can use for JS , similar to @import in CSS.

shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50
2

this code worked for me using jQuery

$.getScript("myscript.js");
mfadel
  • 887
  • 12
  • 32
1

Ther is this plugin http://code.google.com/p/jquery-include/. This jQuery plugin provides browser based file include similar to SSI.

$(document).includeReady(function () {

        // initialisation code here
        // e.g. modify include dom

});

And to use it

<span data-src="includes/test1.html">

        <p class="error-msg">include has not loaded</p>

</span>
Gandalf
  • 1
  • 29
  • 94
  • 165