How to make script execution wait until jquery is loaded - javascript
I am having a problem where the page is loading so fast, that jquery hasn't finished loading before it is being called by a subsequent script. Is there a way to check for the existence of jquery and if it doesn't exist, wait for a moment and then try again?
In response to the answers/comments below, I am posting some of the markup.
The situation... asp.net masterpage and childpage.
In the masterpage, I have a reference to jquery.
Then in the content page, I have a reference to the page-specific script.
When the page specific script is being loaded, it complains that "$ is undefined".
I put alerts at several points in the markup to see the order in which things were firing, and confirmed that it fires in this order:
Master page header.
Child page content block 1 (located inside the
head of the masterpage, but after the masterpage scripts are
called).
Child page content block 2.
Here is the markup at the top of the masterpage:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Reporting Portal</title>
<link href="~/Styles/site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/red/red.css" rel="stylesheet" type="text/css" />
<script type="text/Scripts" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/Scripts" language="javascript" src="../Scripts/jquery.dropdownPlain.js"></script>
<script type="text/Scripts" language="javascript" src="../Scripts/facebox.js"></script>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
Then in the body of the masterpage, there is an additional ContentPlaceHolder:
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
In the child page, it looks like so:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Dashboard.aspx.cs" Inherits="Data.Dashboard" %>
<%# Register src="../userControls/ucDropdownMenu.ascx" tagname="ucDropdownMenu" tagprefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link rel="stylesheet" type="text/css" href="../Styles/paserMap.css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
***CONTENT HERE***
<script src="../Scripts/Dashboard.js" type="text/javascript"></script>
</asp:Content>
Here is the content of the "../Script/Dashboard.js" file:
$(document).ready(function () {
$('.tgl:first').show(); // Show the first div
//Description: East panel parent tab navigation
$('.tabNav label').click(function () {
$('.tabNav li').removeClass('active')
$(this).parent().addClass('active');
var index = $(this).parent('li').index();
var divToggle = $('.ui-layout-content').children('div.tgl');
//hide all subToggle divs
divToggle.hide();
divToggle.eq(index).show();
});
});
Late to the party, and similar to Briguy37's question, but for future reference I use the following method and pass in the functions I want to defer until jQuery is loaded:
function defer(method) {
if (window.jQuery) {
method();
} else {
setTimeout(function() { defer(method) }, 50);
}
}
It will recursively call the defer method every 50ms until window.jQuery exists at which time it exits and calls method()
An example with an anonymous function:
defer(function () {
alert("jQuery is now loaded");
});
the easiest and safest way is to use something like this:
var waitForJQuery = setInterval(function () {
if (typeof $ != 'undefined') {
// place your code here.
clearInterval(waitForJQuery);
}
}, 10);
you can use the defer attribute to load the script at the really end.
<script type='text/javascript' src='myscript.js' defer='defer'></script>
but normally loading your script in correct order should do the trick, so be sure to place jquery inclusion before your own script
If your code is in the page and not in a separate js file so you have to execute your script only after the document is ready and encapsulating your code like this should work too:
$(function(){
//here goes your code
});
Yet another way to do this, although Darbio's defer method is more flexible.
(function() {
var nTimer = setInterval(function() {
if (window.jQuery) {
// Do something with jQuery
clearInterval(nTimer);
}
}, 100);
})();
You can try onload event. It raised when all scripts has been loaded :
window.onload = function () {
//jquery ready for use here
}
But keep in mind, that you may override others scripts where window.onload using.
I have found that suggested solution only works while minding asynchronous code. Here is the version that would work in either case:
document.addEventListener('DOMContentLoaded', function load() {
if (!window.jQuery) return setTimeout(load, 50);
//your synchronous or asynchronous jQuery-related code
}, false);
edit
Could you try the correct type for your script tags?
I see you use text/Scripts, which is not the right mimetype for javascript.
Use this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="../Scripts/jquery.dropdownPlain.js"></script>
<script type="text/javascript" src="../Scripts/facebox.js"></script>
end edit
or you could take a look at require.js which is a loader for your javascript code.
depending on your project, this could however be a bit overkill
Use:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Check out this for more info: http://www.learningjquery.com/2006/09/introducing-document-ready
Note: This should work as long as the script import for your JQuery library is above this call.
Update:
If for some reason your code is not loading synchronously (which I have never run into, but apparently may be possible from the comment below should not happen), you could code it like the following.
function yourFunctionToRun(){
//Your JQuery goodness here
}
function runYourFunctionWhenJQueryIsLoaded() {
if (window.$){
//possibly some other JQuery checks to make sure that everything is loaded here
yourFunctionToRun();
} else {
setTimeout(runYourFunctionWhenJQueryIsLoaded, 50);
}
}
runYourFunctionWhenJQueryIsLoaded();
It's a common issue, imagine you use a cool PHP templating engine, so you have your base layout:
HEADER
BODY ==> dynamic CONTENT/PAGE
FOOTER
And of course, you read somewhere it's better to load Javascript at the bottom of the page, so your dynamic content doesnot know who is jQuery (or the $).
Also you read somewhere it's good to inline small Javascript, so imagine you need jQuery in a page, baboom, $ is not defined (.. yet ^^).
I love the solution Facebook provides
window.fbAsyncInit = function() { alert('FB is ready !'); }
So as a lazy programmer (I should say a good programmer ^^), you can use an equivalent (within your page):
window.jqReady = function() {}
And add at the bottom of your layout, after jQuery include
if (window.hasOwnProperty('jqReady')) $(function() {window.jqReady();});
Rather than "wait" (which is usually done using setTimeout), you could also use the defining of the jQuery object in the window itself as a hook to execute your code that relies on it. This is achievable through a property definition, defined using Object.defineProperty.
(function(){
var _jQuery;
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function($) {
_jQuery = $;
// put code or call to function that uses jQuery here
}
});
})();
I'm not super fond of the interval thingies. When I want to defer jquery, or anything actually, it usually goes something like this.
Start with:
<html>
<head>
<script>var $d=[];var $=(n)=>{$d.push(n)}</script>
</head>
Then:
<body>
<div id="thediv"></div>
<script>
$(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
Then finally:
<script>for(var f in $d){$d[f]();}</script>
</body>
<html>
Or the less mind-boggling version:
<script>var def=[];function defer(n){def.push(n)}</script>
<script>
defer(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>for(var f in def){def[f]();}</script>
And in the case of async you could execute the pushed functions on jquery onload.
<script async onload="for(var f in def){def[f]();}"
src="jquery.min.js" type="text/javascript"></script>
Alternatively:
function loadscript(src, callback){
var script = document.createElement('script');
script.src = src
script.async = true;
script.onload = callback;
document.body.appendChild(script);
};
loadscript("jquery.min", function(){for(var f in def){def[f]();}});
Let's expand defer() from Dario to be more reusable.
function defer(toWaitFor, method) {
if (window[toWaitFor]) {
method();
} else {
setTimeout(function () { defer(toWaitFor, method) }, 50);
}
}
Which is then run:
function waitFor() {
defer('jQuery', () => {console.log('jq done')});
defer('utag', () => {console.log('utag done')});
}
I don't think that's your problem. Script loading is synchronous by default, so unless you're using the defer attribute or loading jQuery itself via another AJAX request, your problem is probably something more like a 404. Can you show your markup, and let us know if you see anything suspicious in firebug or web inspector?
Check this:
https://jsfiddle.net/neohunter/ey2pqt5z/
It will create a fake jQuery object, that allows you to use the onload methods of jquery, and they will be executed as soon as jquery is loaded.
It's not perfect.
// This have to be on <HEAD> preferibly inline
var delayed_jquery = [];
jQuery = function() {
if (typeof arguments[0] == "function") {
jQuery(document).ready(arguments[0]);
} else {
return {
ready: function(fn) {
console.log("registering function");
delayed_jquery.push(fn);
}
}
}
};
$ = jQuery;
var waitForLoad = function() {
if (typeof jQuery.fn != "undefined") {
console.log("jquery loaded!!!");
for (k in delayed_jquery) {
delayed_jquery[k]();
}
} else {
console.log("jquery not loaded..");
window.setTimeout(waitForLoad, 500);
}
};
window.setTimeout(waitForLoad, 500);
// end
// now lets use jQuery (the fake version)
jQuery(document).ready(function() {
alert('Jquery now exists!');
});
jQuery(function() {
alert('Jquery now exists, this is using an alternative call');
})
// And lets load the real jquery after 3 seconds..
window.setTimeout(function() {
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);
}, 3000);
A tangential note on the approaches here that load use setTimeout or setInterval. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready still works, though, so you can embed your usual
jQuery(document).ready(function ($) { ... }
inside your setTimeout or setInterval and everything should work as normal.
Related
How to ensure Javascript file loads after event listener triggers?
I currently have an event listener that listens for something to trigger. I would like for the event to trigger before trying to load the js file. Right now the JavaScript is loading and then the api is ready. How can I get the EventListener to fully complete before the main.js file loads? <head> <title>Default</title> <script>document.addEventListener(apikey,function () { console.log("ready"); }); </script> <script src="./js/main.js"></script> <script>console.log("js loaded")</script> </head>
Remove the script tag to main.js. Inside your event listener function, create and add a script tag to the document: Your code should look like: <head> <title>Default</title> <script> document.addEventListener(apikey, function() { const myscript = document.createElement('script'); myscript.src = './js/main.js'; document.body.appendChild(myscript); }); </script> <script> console.log("js loaded") </script> </head>
You can do something like this: <head> <link href="./js/main.js" rel="preload" as="script"> <script> async function runScript(src) { let script = document.createElement('script'); script.src = src; document.head.append(script); } document.addEventListener(apikey, () => { runScript('./js/main.js'); }); </script> </head> The advantage of this approach is that the script will start loading immediately, regardless of the event. And it can be called from the event without wasting extra time. Browser compatibility: preload.
Call function in .js file from html?
Is it possible to call a function declared in a .js file from the body of the HTML. I'm assuming the reason it won't work is because the .js file is called after the function has been called in the HTML body. Is there a way around this. I've had a look at some answers here, but can't seem to find what I'm looking for. My apologies if it's staring at me as a beginner I may not be using the correct terminology. jqueryfunctions.js: function someFunction() { // do.something; } index.html: <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script> <script src="jqueryfunctions.js"></script> </head> <body> <script> someFunction(); </script> </body> </html> Here is the full/actual .js file returnedMessage() is the function I was reffering to as someFunction(). The console error I'm getting is "returnedMessage() is not defined". $(function(){ var timer = null; function appendmessageBox() { $('body').append('<div id="messageBox" class="datamessagebox"> </div> '); } // just before body tag. appendmessageBox(); // makes MessageBox Disappear on MouseOver $('#messageBox').on('mouseover click', function(){ $(this).fadeOut(300); }); function returnedMessage(message) { if (timer) { clearTimeout(timer); //cancel the previous timer. timer = null; } $( '#messageBox' ).css('display', 'inline-block'); timer = setTimeout(function(){ $( '#messageBox' ).fadeOut( 499 ); }, 5000); $( '#messageBox' ).append('<msg>'+message+'<br /></msg>').fadeIn( 200 ); $( '#messageBox > msg:last-of-type' ).delay(3000).fadeOut( 3000 ); setTimeout(function(){ $( '#messageBox > msg:first-of-type' ).remove(); }, 5999); } // This test message bellow works correctly. returnedMessage('hello world - test 1'); });
EDIT: you should define your function like so: var someFunction = function() { // do something } Or like so function someFunction() { // do something } But always use the function word. More information on function definition in Javascript. More about JS file import Javascript code is inserted between <script> tags in an HTML file <script> console.log("Hello World!"); </script> You usually place those script tags inside the <head> tag. However it's recommended you put them after your <body>. This way you allow the DOM to load before you run your JS script. This is important for exemple when you want to select elements in the DOM. If you put the JS code before the actual HTML that creates this element, then JS will not find the element you would be looking for because it doesn't yet exist. Now it's not really efficient to work with script in your HTML code so it's helpful to write JS in .js files and then import them in you HTML file like you would for a CSS file. Use the <script> to do so: <script src="myScript.js"></script> You can use multiple <script> tags to pull in multiple JS files. But you need to be careful of the order you write them. For instance you have a functions.js file that holds all your functions, and a menu.js that handles the menu on your application. You're using functions from the code functions.js in menu.js so you need to import the files in this order: <script src="functions.js"></script> <script src="menu.js"></script> First declared, first loaded.
You can write own function like this: Here you can see simple example: https://jsbin.com/munowupipo/edit?html,output <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Define a Function in jQuery</title> <script src="https://code.jquery.com/jquery-2.1.0.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $.fn.myFunction = function() { alert('You have successfully defined the function!'); } $(".call-btn").click(function(){ $.fn.myFunction(); }); }); </script> </head> <body> <button type="button" class="call-btn">Click Me</button> </body> </html>
Maybe you want to take the function on document is ready, so you must to write: <script> $(document).on("ready", function() { yourfunction(); }); </script>
JavaScript load order and anonymous function
In my html file, I am loading two external javascript files that does some dom manipulation, the first one simply prepares the page (injecting some div and contents) in the html. And the second one locates those divs that were just injected and then try and does some stuffs with it. var app = { init: function () { // event handler goes here app.alertMe('Hello'); app.loadContent(); app.insertDiv(); }, loadContent: function() { $('#div1').load('../html/demo_test.html'); }, insertDiv: function() { $('#div2').append('<strong>YEEEEEEAP</strong>'); }, alertMe: function(a) { alert(a); } }; $(function () { app.init(); }) The second one is this bootstrap library. My html file is as follows <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>A</title> <script type="text/javascript" src="page_prep.js"> </script> </head> <body> body </body> <script type="text/javascript" src="bootstap_lib.js"> </html> Although I have the load order in the right order, the library seem to be loading before my custom.js this end up causing the actions not to work because the divs that need be present are not found. Careful debugging has proven that the divs were getting injected afterwards. Any reason why that might be the case?
You are deferring the injection until the page has completed loading, where the bootstrap script runs as soon as the browser downloads it. Move your script file to just above yout bootstrap script, and change this: $(function () { //This defers execution app.init(); }) to this: app.init(); //This executes immediately
Why is external javascript library blocking javascript on my page?
Here's a very simple question that my simple mind can't answer: why isn't the anonymous and onload function below being run when I load in the external library? I am missing something really, really basic. Library.js has only one line: console.log('library'). How much more basic can one get? <script type="text/javascript" src='js/library.js' /> <script type="text/javascript"> (function () { console.log('anon'); })(); window.onload = function () { console.log('onload'); } (); </script>
Your script syntax is invalid. You should have a separate closing tag instead of the self-closing version. <!--------- v ---------> <script type="text/javascript" src='js/library.js'></script> You also have an issue in that you're invoking the onload function immediately. window.onload = function () { console.log('onload'); }/* () */; // ^^---remove these to assign the function instead of invoking it.
How to add jQuery in JS file
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?
var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.6.3.min.js'; // Check https://jquery.com/ for the current version document.getElementsByTagName('head')[0].appendChild(script);
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"); }); });
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 (function() { var startingTime = new Date().getTime(); // Load the script var script = document.createElement("SCRIPT"); script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; script.type = 'text/javascript'; document.getElementsByTagName("head")[0].appendChild(script); // Poll for jQuery to come into existance var checkReady = function(callback) { if (window.jQuery) { callback(jQuery); } else { window.setTimeout(function() { checkReady(callback); }, 20); } }; // Start polling... checkReady(function($) { $(function() { var endingTime = new Date().getTime(); var tookTime = endingTime - startingTime; window.alert("jQuery is loaded, after " + tookTime + " milliseconds!"); }); }); })(); Other Option : - You can also try Require.JS which is a JS module loader.
/* 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 :)'); }
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" />
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: I have created a js with name jQueryIncluder.js 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
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
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>"); }, 1000);
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
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. Write your jquery code in your javascript file as you would in your html dom Include jquery framework before closing body tag 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>
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('>');
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>
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
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.
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 $.
The latest answer is outdated, try this: var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.6.1.min.js'; document.getElementsByTagName('head')[0].appendChild(script);
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>