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?

4
  • 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? Commented Jan 11, 2016 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 Commented Jan 11, 2016 at 14:38
  • Go checkout this thread you will find the answer stackoverflow.com/questions/18261214/… Commented Jan 11, 2016 at 14:47
  • How to apply external css to divs created in javascript file? Commented Jan 11, 2016 at 14:50

2 Answers 2

2
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
Sign up to request clarification or add additional context in comments.

2 Comments

What is "head" in last line? Why is appendChild required?
the head is referencing the <head> tag in your html.. it should typically be before your <body> tag and its where people usually load script files in html
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.