Load jQuery dynamically - javascript

I am having issues with loading jQuery with Javascript. I need to load it with Javascript because there are conditions that I only can know client-side. The commented out code is supposed to initialize the scripts, but I am having no luck with them.
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
//script_tag.onload = main; // Run main() once jQuery has loaded
//script_tag.onreadystatechange = function () { // Same thing but for IE
//if (this.readyState == 'complete' || this.readyState == 'loaded') main();
//}
document.getElementsByTagName("head")[0].appendChild(script_tag);
http://mybsabusiness.com/samplesites/silver/sbsa01/
This is the site that the problems are on.

From the jQuerify bookmarlet :
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js',function() {
// Yay jQuery is ready \o/
});​

Related

How to add second link to script in JqueryWidget code

I have written a widget and it works great, but right now I am giving my users a link to a remote script, a link to my script and a div to place on their page. I would like to reduce this to just a link to my script and the div. The remote link I want to include in my code below is
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Can anyone please educate me on how to add a second link in my code? I already link to a remote jquery and a remote stylesheet, but I am not sure how/where to include another remote link. I have tried a number of places and ways, but I keep breaking my page, haha. Thanks for any help offered.
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.12.4') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "//code.jquery.com/jquery-1.12.4.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function() { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonURL = "//www.myurl.com/mssql.php/ws_nfy";
jQuery(document).ready(function() {
jQuery.ajax({
url: jsonURL,
success: searchCallback
});
});
function searchCallback(data) {
var ws_nfy = data.ws_nfy.records;
jQuery.each(ws_nfy, function(index, nfy) {
jQuery("#tabs ul").append('<li>' + nfy[2] + '</li>');
jQuery("#tabs ul").after("<div id='tabs-" + nfy[0] + "'>" + nfy[1] + "</div>");
});
$("#tabs").tabs();
};
});
}
})(); // We call our anonymous function immediately
You're checking if jQuery is already loaded before injecting it... Which is good. Now you should do the same for jQuery-UI.
So that's the same procedure...
Try this:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.12.4') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "//code.jquery.com/jquery-1.12.4.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function() {
// For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
//main(); // Not now! Check for UI first.
checkUI();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
//main(); // Not now! Check for UI first.
checkUI();
}
// ========================== Check if jQuery-UI is already loaded
function checkUI(){
if(typeof(jQuery.ui) != "undefined"){
// UI is loaded already.
console.log("UI is defined");
console.log( typeof(jQuery.ui) );
main();
}else{
// UI is not loaded. Got to load it.
console.log("UI is NOT defined");
//console.log( typeof(jQuery.ui) );
var ui = document.createElement('script');
ui.setAttribute("type", "text/javascript");
// For UI
window.$ = jQuery;
ui.setAttribute("src", "https://code.jquery.com/ui/1.12.1/jquery-ui.js");
console.log(ui);
document.getElementsByTagName("head")[0].appendChild(ui);
if (ui.readyState) {
console.log( "READYSTATE" );
ui.onreadystatechange = function() { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
console.log( "STATELOADED" );
main();
}
};
} else {
console.log( "ELSE" );
jQuery(ui).on("load", function(){
console.log("UI loaded...");
main();
});
}
}
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
console.log("jQuery: "+jQuery.fn.jquery+"\njQuery-UI: "+jQuery.ui);
console.log("Tabs element: "+jQuery("#tabs").length);
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonURL = "//www.myurl.com/api.php/ws_nfy";
jQuery.ajax({
url: jsonURL,
success: searchCallback
});
function searchCallback(data) {
var ws_nfy = data.ws_nfy.records;
jQuery.each(ws_nfy, function(index, nfy) {
jQuery("#tabs ul").append('<li>' + nfy[2] + '</li>');
jQuery("#tabs ul").after("<div id='tabs-" + nfy[0] + "'>" + nfy[1] + "</div>");
});
jQuery("#tabs").tabs();
};
});
}
})(); // We call our anonymous function immediately

Set response data from external JS script

I have this script
<script>
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('/script/script.js', function() {
// put your code here to run after script is loaded
});
</script>
And I can't figure out how can I get response data from the script I'm trying to load.
Basically, this script contains a function that does something and then returns some value.
I know that in jQuery analog in would be just data argument in getScript function, but I only have native JS here.
What and where should I add to get response data in my script?
Assuming that your script contains a function declared in a global scope, you can simply include this script and then execute any function / access any member from this script:
After your script has been loaded and executed, you can work with it just like with a simple script which is a part of your current document.
Here is a demo which loads jQuery script from Google CDN and then outputs jQuery version (which is a part of jQuery library):
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
console.log("typeof jQuery: " + typeof jQuery); // jQuery not loaded
loadJS("https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js", function() {
console.log("typeof jQuery: " + typeof jQuery + ", version = " + jQuery.fn.jquery); // jQuery has been loaded
});

can't run jQuery functions after appending jQuery from same file

I'm appending into my page multiple scripts including jQuery, jQuery migrate... all from same .js file
this is how it looks:
function appendScript(pathToScript, run) {
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
if(run == true){
js.onreadystatechange = function () {
if (this.readyState == 'complete') runFunctions();
}
js.onload = runFunctions;
}
js.src = pathToScript;
head.appendChild(js);
}
appendScript("http://code.jquery.com/jquery-latest.min.js");
appendScript("http://code.jquery.com/jquery-migrate-1.3.0.min.js", true);
function runFunctions(){
console.log('test') // all good till here
// here i have only jquery functions
$('#myDiv').addClass('test');
alert("this doesn't work");
....
}
My problem is that I can't run $(document).ready or any jQuery function, only javascript.
Tried with timeout too. Also I already have 1 x $(window).bind("load", function(){...} so I don't need 1 more
Since jQuery Migrate depends on jQuery, you need to wait until loading the next script.
Here is a working example (I also cleaned up some variables).
function appendScript(src, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
if (callback) {
script.onload = callback;
}
script.src = src;
head.appendChild(script);
}
appendScript("https://code.jquery.com/jquery-latest.min.js", function() {
appendScript("https://code.jquery.com/jquery-migrate-1.3.0.min.js", function() {
document.body.innerHTML = 'Loaded jQuery version ' + jQuery.fn.jquery;
});
});
See working jsfiddle.

Js/jQuery include function not working in IE

i have following Code
function includeJSLib(lib, id, callback) {
if (!document.getElementById(id)) {
var s = document.createElement('script');
s.setAttribute('id', id);
s.setAttribute('async', 'false');
s.setAttribute('type', 'text/javascript');
s.src = lib;
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = callback;
} else {
callback();
}
}
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function(){
jQuery(document).ready( function($) {
if ($('body').hasClass('class')) { do something }
});
});
it will load jQuery. In the callback function there is some custom code. the custom code works fine in Firefox and Chrome but not in IE.
The internet Explorer totally ignores the code snippets. Tested in IE 10/11.
Does anybody have a idea what the problem could be?
Thanks & Regards,
Noxx
p.s. The IE Debugger says nothing, it just jumps over the snippets. And i have to include jQuery this way (better dont ask :P)
For IE instead of onload use onreadystatechange:
function includeJSLib(lib, id, callback) {
if (!document.getElementById(id)) {
var s = document.createElement('script');
s.setAttribute('id', id);
s.setAttribute('async', 'false');
s.setAttribute('type', 'text/javascript');
s.src = lib;
document.getElementsByTagName('head')[0].appendChild(s);
var loaded = false;
s.onload = s.onreadystatechange = function() {
var readyState = this.readyState || 'complete';
if (!loaded && ('loaded' === readyState || 'complete' === readyState)) {
loaded = true;
// Handle memory leak in IE
s.onload = s.onreadystatechange = null;
s.parentNode.removeChild(s);
callback();
}
};
// s.onload = callback;
} else {
callback();
}
}
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function() {
jQuery(document).ready( function($) {
if ($('body').hasClass('class')) { do something }
});
});

Run after jQuery version selection is done

I'm trying to find out if a user supports jQuery 2.xThis works fine, but when I try to run a script it doesn't work because jQuery isn't done loading...
How can I trigger __run() after jQuery is done loading.
Init script:
function __run(){
//
// function runs the jQuery website
//
$("body").append( "<p>Test</p>" );
}
(function () {
var s, s0, js;
if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
js = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
} else {
js = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
alert('Woow, that\'s one old browser, maybe you should upgrade. We don\'t support this version, you can try to use the website though');
}
s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = js;
s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(s, s0);
__run();
}());
Try this
(function () {
var s, s0, js;
if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
js = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
} else {
js = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
alert('Woow, that\'s one old browser, maybe you should upgrade. We don\'t support this version, you can try to use the website though');
}
s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = js;
s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(s, s0);
s.onreadystatechange= function () {
if (this.readyState == 'complete') __run();
}
s.onload= __run;
}());
Check with onreadystatechange
s.onload = s.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
__run();
}
};

Categories