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?
This question is related to
javascript
jquery
it is not possible to import js file inside another js file
The way to use jquery inside js is
import the js in the html or whatever view page you are using inside which you are going to include the js file
view.html
<script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
<script src="<%=request.getContextPath()%>/js/default.js"></script>
default.js
$('document').ready(function() {
$('li#user').click(function() {
$(this).addClass('selectedEmp');
});
});
this will definitely work for you
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?
If you want to include jQuery code from another JS file, this should do the trick:
I had the following in my HTML file:
<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>
I created a separate my_jquery.js file with the following:
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
$(this).hide("slow");
});
});
/* Adding the script tag to the head as suggested before */
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "http://code.jquery.com/jquery-2.2.1.min.js";
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = handler;
script.onload = handler;
// Fire the loading
head.appendChild(script);
function handler(){
console.log('jquery added :)');
}
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>
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);
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>');
Here is the solution, that I adopted as a combination of some proposed solutions in some other forums.
This way you can reference both css files and other js files in one js file, thus making change next time only in a single place. Please let me know if you have any concerns on it.
I have done following:
declared and executed following code in this file
function getVirtualDirectory() {
var vDir = document.location.pathname.split('/');
return '/' + vDir[1] + '/';
}
function include_jQueryFilesToPage() {
var siteAddress = location.protocol + '//' + document.location.hostname + getVirtualDirectory();
var jqCSSFilePath = siteAddress + 'includes/jQueryCSS/ehrgreen-theme/jquery-ui-1.8.2.custom.css';
var jqCoreFilePath = siteAddress + 'includes/jquery-1.4.1.min.js';
var jqUIFilePath = siteAddress + 'includes/jquery-ui-1.8.2.custom.min.js';
var head = document.getElementsByTagName('head')[0];
// jQuery CSS jnclude
var jqCSS = 'cssIDJQ'; // you could encode the css path itself to generate id.
if (!document.getElementById(jqCSS)) {
var link = document.createElement('link');
link.id = jqCSS;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = jqCSSFilePath;
link.media = 'all';
head.appendChild(link);
}
// Core jQuery include
var jqc = "coreFileRefIDJQ";
if (!document.getElementById(jqc))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqc + '" src="' + jqCoreFilePath + '"></scr' + 'ipt>');
// jQueryUI include
var jqUI = "uiFileRefIDJQ";
if (!document.getElementById(jqUI))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqUI + '" src="' + jqUIFilePath + '"></scr' + 'ipt>');
}
include_jQueryFilesToPage();
I referenced the above jQueryIncluder.js file in another js or xsl file of my .Net project as following:
<script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
I hope my effort is appreciated.
Thanks
Theres a plugin for jquery where you can just include the files you need into some other js file, here is the link for it http://tobiasz123.wordpress.com/2007/08/01/include-script-inclusion-jquery-plugin/.
Also this document.write line will write the script tags in the html not in your js file.
So I hope this could help you out, a little with your problem
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.
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>
I find that the best way is to use this...
**<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>**
This is from the Codecademy 'Make an Interactive Website' project.
You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.
// Anonymous "self-invoking" function_x000D_
(function() {_x000D_
var startingTime = new Date().getTime();_x000D_
// Load the script_x000D_
var script = document.createElement("SCRIPT");_x000D_
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';_x000D_
script.type = 'text/javascript';_x000D_
document.getElementsByTagName("head")[0].appendChild(script);_x000D_
_x000D_
// Poll for jQuery to come into existance_x000D_
var checkReady = function(callback) {_x000D_
if (window.jQuery) {_x000D_
callback(jQuery);_x000D_
}_x000D_
else {_x000D_
window.setTimeout(function() { checkReady(callback); }, 20);_x000D_
}_x000D_
};_x000D_
_x000D_
// Start polling..._x000D_
checkReady(function($) {_x000D_
$(function() {_x000D_
var endingTime = new Date().getTime();_x000D_
var tookTime = endingTime - startingTime;_x000D_
window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");_x000D_
});_x000D_
});_x000D_
})();
_x000D_
Other Option : - You can also try Require.JS which is a JS module loader.
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
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();_x000D_
_x000D_
function init()_x000D_
{_x000D_
addJQuery();_x000D_
addBodyAndOnLoadScript();_x000D_
addCSS();_x000D_
}_x000D_
_x000D_
function addJQuery()_x000D_
{_x000D_
var head = document.getElementsByTagName( 'head' )[0];_x000D_
var scriptjQuery = document.createElement( 'script' );_x000D_
scriptjQuery.type = 'text/javascript';_x000D_
scriptjQuery.id = 'jQuery'_x000D_
scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';_x000D_
var script = document.getElementsByTagName( 'script' )[0];_x000D_
head.insertBefore(scriptjQuery, script);_x000D_
}_x000D_
_x000D_
function addBodyAndOnLoadScript()_x000D_
{_x000D_
var body = document.createElement('body')_x000D_
body.onload = _x000D_
function()_x000D_
{_x000D_
onloadFunction();_x000D_
};_x000D_
}_x000D_
_x000D_
function addCSS()_x000D_
{_x000D_
var head = document.getElementsByTagName( 'head' )[0];_x000D_
var linkCss = document.createElement( 'link' );_x000D_
linkCss.rel = 'stylesheet';_x000D_
linkCss.href = 'E:/Temporary_files/temp_css.css';_x000D_
head.appendChild( linkCss );_x000D_
}_x000D_
_x000D_
function onloadFunction()_x000D_
{_x000D_
var body = $( 'body' );_x000D_
body.append('<strong>Hello world</strong>');_x000D_
}
_x000D_
html _x000D_
{_x000D_
background-color: #f5f5dc;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Temp Study HTML Page</title>_x000D_
<script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>_x000D_
</head>_x000D_
<body></body>_x000D_
</html>
_x000D_
If you frequently want to update your jquery file link to a new version file, across your site on many pages, at one go..
Create a javascript file (.js) and put in the below code, and map this javascript file to all the pages (instead of mapping jquery file directly on the page), so when the jquery file link is updated on this javascript file it will reflect across the site.
The below code is tested and it works good!
document.write('<');
document.write('script ');
document.write('src="');
//next line is the path to jquery file
document.write('/javascripts/jquery-1.4.1.js');
document.write('" type="text/javascript"></');
document.write('script');
document.write('>');
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
In if you want to add reference to any js file, say, from your project, you may also add it directly using reference tag, in Visual Studio IDE this is handled automatically by dragging and dropping the external file from solution explorer to current file (This works for mark up files, .js & .css files too)
/// <reference path="jquery-2.0.3.js" />
You can create a master page base without included js and jquery files. Put a content place holder in master page base in head section, then create a nested master page that inherits from this master page base. Now put your includes in a asp:content in nested master page, finally create a content page from this nested master page
Example:
//in master page base
<%@ master language="C#" autoeventwireup="true" inherits="MasterPage" codebehind="MasterPage.master.cs" %>
<html>
<head id="Head1" runat="server">
<asp:ContentPlaceHolder runat="server" ID="cphChildHead">
<!-- Nested Master Page include Codes will sit Here -->
</asp:ContentPlaceHolder>
</head>
<body>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<!-- some code here -->
</body>
</html>
//in nested master page :
<%@ master language="C#" masterpagefile="~/MasterPage.master" autoeventwireup="true"
codebehind="MasterPageLib.master.cs" inherits="sampleNameSpace" %>
<asp:Content ID="headcontent" ContentPlaceHolderID="cphChildHead" runat="server">
<!-- includes will set here a nested master page -->
<link href="../CSS/pwt-datepicker.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery-1.9.0.min.js" type="text/javascript"></script>
<!-- other includes ;) -->
</asp:Content>
<asp:Content ID="bodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ContentPlaceHolder ID="cphChildBody" runat="server" EnableViewState="true">
<!-- Content page code will sit Here -->
</asp:ContentPlaceHolder>
</asp:Content>
Source: Stackoverflow.com