How to add jQuery in JS file

Viewed 583964

I have some code specific to sorting tables. Since the code is common in most pages I want to make a JS file which will have the code and all the pages using it can reference it from there.

Problem is: How do I add jQuery, and table sorter plugin into that .js file?

I tried something like this:

document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');

but this seems to not work.

What is the best way to do this?

20 Answers
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
document.getElementsByTagName('head')[0].appendChild(script);

The problem is you're using </script> within the script, which is ending the script tag. Try this:

document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></sc'+'ript>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></sc'+'ript>');

I believe what you want to do is still to incude this js file in you html dom, if so then this apporach will work.

  1. Write your jquery code in your javascript file as you would in your html dom
  2. Include jquery framework before closing body tag
  3. Include javascript file after including jqyery file

Example: //js file

     $(document).ready(function(){
     alert("jquery in js file");
     });

//html dom

    <body>
   <!--some divs content--->

   <script src=/path/to/jquery.js ></script>
   <script src=/path/to/js.js ></script>
   </body>

The following answer was posted previously by another user, but provided no explanation so I decided to annotate what is happening.

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);

Explanation

The problem is solved by creating a script element in JavaScript, and then setting the src attribute to the path of the jQuery file.

var jQueryScript = document.createElement('script');

Above we create the script element.

Next we set the src attribute to the path as explained before. This can be set to

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

or

/your/path/to/jquery/file

In use:

jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');

Last, but not least, appending the new element to the document head:

document.head.appendChild(jQueryScript);

or body:

document.body.appendChild(jQueryScript);

In Use

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);

setTimeout(function() {
  // Add the rest of your code here, as we have to wait a moment before the document has jQuery as a part of it.
  $("body").html("<h1>It Works!</h1>");
}, 100);

Dynamic adding jQuery, CSS from js file. When we added onload function to body we can use jQuery to create page from js file.

init();

function init()
{
 addJQuery();
 addBodyAndOnLoadScript();
 addCSS();
}

function addJQuery()
{
 var head = document.getElementsByTagName( 'head' )[0];
 var scriptjQuery = document.createElement( 'script' );
 scriptjQuery.type = 'text/javascript';
 scriptjQuery.id = 'jQuery'
 scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
 var script = document.getElementsByTagName( 'script' )[0];
 head.insertBefore(scriptjQuery, script);
}

function addBodyAndOnLoadScript()
{
 var body = document.createElement('body')
 body.onload = 
 function()
 {
  onloadFunction();
 };
}

function addCSS()
{
 var head = document.getElementsByTagName( 'head' )[0];
 var linkCss = document.createElement( 'link' );
 linkCss.rel = 'stylesheet';
 linkCss.href = 'E:/Temporary_files/temp_css.css';
 head.appendChild( linkCss );
}

function onloadFunction()
{
 var body = $( 'body' );
 body.append('<strong>Hello world</strong>');
}
html 
{
 background-color: #f5f5dc;
}
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Temp Study HTML Page</title>
  <script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>
 </head>
 <body></body>
</html>

If document.write('<\script ...') isn't working, try document.createElement('script')...

Other than that, you should be worried about the type of website you're making - do you really think its a good idea to include .js files from .js files?

just copy the code from the two files into your file at the top.

or use something like this http://code.google.com/p/minify/ to combine your files dynamically.

Josh

After lots of research, I solve this issue with hint from ofir_aghai answer about script load event.

Basically we need to use $ for jQuery code, but we can't use it till jQuery is loaded. I used document.createElement() to add a script for jQuery, but the issue is that it takes time to load while the next statement in JavaScript using $ fails. So, I used the below solution.

myscript.js is having code which uses jQuery main.js is used to load both jquery.min.js and myscript.js files making sure that jQuery is loaded.

main.js code

window.load = loadJQueryFile();
var heads = document.getElementsByTagName('head');

function loadJQueryFile(){
    var jqueryScript=document.createElement('script');
    jqueryScript.setAttribute("type","text/javascript");
    jqueryScript.setAttribute("src", "/js/jquery.min.js");

    jqueryScript.onreadystatechange = handler;
    jqueryScript.onload = handler;  
    heads[0].appendChild(jqueryScript);
}

function handler(){
    var myScriptFile=document.createElement('script');
    myScriptFile.setAttribute("type","text/javascript");
    myScriptFile.setAttribute("src", "myscript.js");
    heads[0].appendChild(myScriptFile);
 }

This way it worked. Using loadJQueryFile() from myscript.js didn't work. It immediately goes to the next statement which uses $.

var jQueryScript = document.createElement('script');  
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);

Why are you using Javascript to write the script tags? Simply add the script tags to your head section. So your document will look something like this:

<html>
  <head>
    <!-- Whatever you want here -->
    <script src="/javascripts/jquery.js" type="text/javascript"></script>
    <script src="/javascripts/jquery.tablesorter.js" type="text/javascript"></script>
  </head>
  <body>
    The contents of the page.
  </body>
</html>
Related