0

How to include jquery libray src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" in an xternal .js file? Also how to include .css file in .js file?

Jaideep
  • 25
  • 6
  • Hi Jaideep, the question seems to be unclear. Can you post examples of what you have tried so far / or what you are trying to achieve? – dubes Jan 11 '16 at 14:36
  • I just want to include jquery lib in javascript file, because I want to write jquery code in javascript. Also i want to apply external css to divs that i create in javascript file – Jaideep Jan 11 '16 at 14:38
  • Go checkout this thread you will find the answer http://stackoverflow.com/questions/18261214/load-external-js-file-in-another-js-file – Danyal Fayyaz Jan 11 '16 at 14:47
  • How to apply external css to divs created in javascript file? – Jaideep Jan 11 '16 at 14:50

2 Answers2

2
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
gegillam
  • 126
  • 7
  • What is "head" in last line? Why is appendChild required? – Jaideep Jan 11 '16 at 14:43
  • the head is referencing the tag in your html.. it should typically be before your tag and its where people usually load script files in html – gegillam Jan 11 '16 at 14:56
0

You can only add JS files in HTML files. When you run a JS App open a website you're viewing the HTML file which has the JS files included.

If you're using jQuery you can add a JS file to HTML using :

 $.getScript(url, successCallback);

And here's' an async Vanilla JS function

function loadScript(src, callback)
{
  var s,
      r,
      t;
  r = false;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function() {
    //console.log( this.readyState ); //uncomment this line to see which ready states are called.
    if ( !r && (!this.readyState || this.readyState == 'complete') )
    {
      r = true;
      callback();
    }
  };
  t = document.getElementsByTagName('script')[0];
  t.parentNode.insertBefore(s, t);
}

Or just write all your code in one file or use build systems to concat and minify your files for production.

Ali Mousavi
  • 855
  • 7
  • 15