I was working on the jQuery plugin by using jQuery UI. In this script http://alexmarandon.com/articles/web_widget_jquery/
Author is only checking whether jQuery library added is or not. But I need to check for both jQuery and jQuery UI.
If not loaded then load it. When I tried to do this then due to synchronous process I get error jQuery/jQuery-ui is not defined can you please help me with that.
Thanks
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.10.2') {
console.log('In if of index js');
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"https://code.jquery.com/jquery-1.10.2.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
loadui();
} else {
console.log('Index end of first if');
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
// main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
console.log('Index loaded');
// 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
loadui();
}
function script2LoadHandler() {
console.log('Index2 loaded');
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
main()
}
/******** Our main function ********/
function main() {
setTimeout(myFunction, 3000);
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"js/scripts.js");
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
function myFunction(){
console.log("asdasdasdasdas");
}
function loadui(){
console.log('Loadui2');
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"https://code.jquery.com/ui/1.10.4/jquery-ui.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
main();
}
})();
This is how to check whether library loaded or not
var s;
if (typeof jQuery === 'undefined'){
// jquery not loaded
s = document.createElement('script');
s.src = "https://code.jquery.com/jquery-3.2.1.js";
document.head.appendChild(s);
}
if (typeof jQuery.ui === 'undefined'){
// jquery ui not loaded
s = document.createElement('script');
s.src = "https://code.jquery.com/ui/1.12.1/jquery-ui.js";
document.head.appendChild(s);
}
This is how to load one can load one after another when there is dependency.
var s;
if (typeof jQuery === 'undefined') {
// jquery not loaded
s = document.createElement('script');
s.src = "https://code.jquery.com/jquery-3.2.1.js";
document.head.appendChild(s);
// jquery load
s.onload = function() {
// jquery ui you cant load without jquery so
s = document.createElement('script');
s.src = "https://code.jquery.com/ui/1.12.1/jquery-ui.js";
document.head.appendChild(s);
// jquery version
console.log(jQuery.fn.jquery);
// jquery ui load
s.onload = function() {
// jquery ui version
console.log(jQuery.ui.version);
}
}
}
As answered in this post you can do a condition by checking its type
if (typeof jQuery != "undefined"){ //check if jQuery Exists
if (typeof jQuery.ui != "undefined"){ //check if jQueryui library has been loaded
}
}
Related
I'm facing an error with loading the Bootstrap library as it always gives this error:
Uncaught Error: Bootstrap's JavaScript requires jQuery
Despite that I'm attaching the Bootstrap library after making sure the jQuery is loaded but still getting the error.
I'm using the following code to attach the jQuery to the page by creating the element and append it to the document:
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.1.1') {
console.log("jQuery LOADED");
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
console.log(window.jQuery.fn.jquery);
scriptLoadHandler();
}
};
} else {
console.log("ONLOAD STATE");
script_tag.onload = scriptLoadHandler;
}
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
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();
}
Here I'm creating the Bootstrap after document is being ready:
function main() {
jQuery(document).ready(function ($) {
var bootstrap_script = document.createElement('script');
bootstrap_script.setAttribute("type", "text/javascript");
bootstrap_script.setAttribute("src",
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(bootstrap_script);
})
}
Just to clarify a critical thing
I'm writing the js code in a separated js file, because I want to use later as a jQuery plugin. Thus, I'm trying to attach the libraries as I don't guarantee that the targeted page would include those libraries or not
you have a missing ")}" in your "main" function. after correcting this, bootstrap loads successfully for me without giving any error. I'm using firefox 50.1.0
here is your code that works for me:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>document</title>
</head>
<body>
<script>
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.1.1') {
console.log("jQuery LOADED");
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
console.log(window.jQuery.fn.jquery);
scriptLoadHandler();
}
};
} else {
console.log("ONLOAD STATE");
script_tag.onload = scriptLoadHandler;
}
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
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();
}
function main() {
jQuery(document).ready(function ($) {
var bootstrap_script = document.createElement('script');
bootstrap_script.setAttribute("type", "text/javascript");
bootstrap_script.setAttribute("src",
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(bootstrap_script);
})
}
</script>
</body>
</html>
Try to load jquery using https
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
Hope it'll work.
The problem is that you are using a higher version. Use this version:
http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
Why make it so complicated?
Just add this inside your <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" ></script>
Or add it last in your document to enable a faster load. You then need to use document ready on your scripts so they don't run before the jQuery has been loaded.
I have loaded my jquery library in my plug in from javascript and getting an error $ is not defined if I call my plug in anonymous function from another javscript page
Following is my work
(function () {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.11.3') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.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();
// Call our main function
main();
}
/******** Our main function ********/
function main() {
// Add some validation here to make sure UI is not loaded etc...
jQuery.getScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js');
jQuery(document).ready(function ($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "StyleSheet.css"
});
css_link.appendTo('head');
//loading plug in
"use strict";
$.fn.myplugin = function (options) {
var settings = $.extend({
//default
isstatic: false
});
var options = $.extend(settings, options);
var images = ['http://www.example1.com'/1.png, 'http://www.example2.com/final.gif'];
//Iterate over the current set of matched elements
return this.each(function () {
var obj = $('.div2');
obj.hide();
$(this).show();
$(this).click(function () {
obj.toggle("slow");
if (options.isstatic) {
$(".image-class").attr("src", images[0]);
options.isstatic = false;
}
else {
$(".image-class").attr("src", images[1]);
options.isstatic = true;
}
});
});
return options.isstatic = false;
}
});
}
})();
I am calling it using another file.js
$(document).ready(function () {
$('#mydiv').myplugin();
});
I am getting an error here $ is no defined how to remove this error may b I have done something wrong with jQuery variable or $ in javascript file
I guess you need jquery for further scripts in your page or for your plugin to run, so jquery reference should be the first one in the head, could you try replacing the part of your code
( document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(script_tag)
with
var head=( document.getElementsByTagName("head")[0] || document.documentElement ); head.insertBefore(script_tag,head.firstChild);
How to correctly load jQuery library if it is not loaded yet?
somepage.html:
<script src="http://example.com/js/widget_init.js" type="text/javascript"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
console.log('ERROR: NOT LOADED');
}
else{
console.log('OK');
}
</script>
The script 'widget_init.js' should load jQuery if it is not loaded yet.
I have this script 'widget_init.js':
function load_script_jquery(){
if (typeof jQuery == 'undefined') {
var jq = document.createElement('script'); jq.type = 'text/javascript';
jq.src = '/path/to/js/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
else {
}
}
load_script_jquery();
// some other code
The problem is that it doesn't wait for jQuery to be loaded and it shows error like this:
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
console.log('ERROR: NOT LOADED'); // NOT LOADED
}
else{
console.log('OK'); // NEVER GOES HERE
}
</script>
I tried this also without any effect:
document.write('<script src="/path/to/js/jquery.min.js" type="text/javascript"><\/script>');
How to wait until jQuery is loaded so I can use it ?
Your code to append the jQuery script will be appended after your <script> snippet that checks for it. That's how .appendChild works
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node
Source: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild (emphasis mine)
Here are two options to solve this:
If you can insert HTML on the page
You can use this snippet from the HTML5 Boilerplate. It will check if another script has already loaded jQuery, and if not, will load it inline.
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
Just drop it in your head or body tag before the script that depends on it.
If you need to dynamically load it in the Javascript source
Follow the instructions in this tutorial
(function () {
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
//jQuery loaded
console.log('jquery loaded');
});
})();
You just need callback function, after loading jquery secessfully:
var loadJS = function(url, cb) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
url);
if (script_tag.readyState) {
script_tag.onreadystatechange = function() { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
cb();//calling callback
}
};
} else { // Other browsers
script_tag.onload = cb;//calling callback function
}
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
};
And simply call this function with jquery library path and callback function reference:
loadJS(hostUrl + "/js/libraries/jquery.js", callback);
I want to provide my clients a simple code to insert and get my plugin.
The code:
<div id='banner-lujanventas'></div>
<script src="http://lujanventas.com/plugins/banners/script.js" type="text/javascript"></script>
The problem is that my plugin only works with jQuery. How do I check if a version of jQuery is installed on my script.js file and if not include it? (I can only modify my /script.js file)
Make your own script element :
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
//edit
window.onload = function() {
$(function(){ alert("jQuery + DOM loaded."); });
}
You must put your real onload code in a window.onload() function, and NOT in a $(document).ready() function, because jquery.js is not necessary loaded at this time.
You can check for the jQuery variable
if (typeof jQuery === 'undefined') {
// download it
}
For downloading options, e.g. asynchronous vs. document.write, check out this article.
Something like this:
<script>!window.jQuery && document.write(unescape('%3Cscript src="http://yourdomain.com/js/jquery-1.6.2.min.js"%3E%3C/script%3E'))</script>
I dug up some old code that looks for a particular version of jQuery and loads it if it's not found plus it avoids conflicting with any existing jQuery the page already uses:
// This handles loading the correct version of jQuery without
// interfering with any other version loaded from the parent page.
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-2.1.0.min.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
}
})(window, document, "2.1", function($) {
$(document).ready(function() {
console.log("Using jQuery version: " + $.fn.jquery);
// Your code goes here...
});
});
I'm developing a javascript widget that depends on jQuery. The widget may or may not be loaded onto a page that already has jQuery loaded. There are many problems that come up in this case...
If the web page does not have jQuery, I must load my own jQuery. There seems to be a delicate timing issue when doing this, however. For example, if my widget loads and executes before jQuery is finished loading and executing, I get a jQuery is not defined error.
If the web page does have jQuery, I can usually work with it. If the jQuery version is old, however, I would like to load my own. If I do load my own, however, I need to do it in such a way as to not stomp on their $ variable. If I set jQuery.noConflict() and any of their scripts depend on $, then I have just broken their page.
If the web page uses another javascript library (e.g. prototype), I needed to be sensitive of prototype's $ variable also.
Because of all of the above, it is seeming easier to not depend on jQuery. But before I go down that road, which will involve mostly rewriting my widget code, I wanted to ask for advice first.
The basic skeleton of my code, including the timing bug and sometimes $ bugs, follows:
<script type="text/javascript" charset="utf-8">
// <![CDATA
if (typeof jQuery === 'undefined') {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '{{ URL }}/jquery.js';
head.appendChild(script);
}
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>
My widget has the following structure:
(function($) {
var mywidget = {
init: function() {
...
}
};
$(document).ready(function() {
mywidget.init();
});
})(jQuery);
If there are any pointers or resources for achieving a widget that can work in all the mentioned environments, they would be greatly appreciated.
After reviewing some answers and pointers, and finding some helpful jQuery hackers, I ended up with something like the following:
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "/media/jquery.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
}
})(window, document, "1.3", function($, jquery_loaded) {
// Widget code here
});
This will load jQuery if it's not already loaded and encapsulates it in the callback so it doesn't conflict with a pre-existing jQuery on the page. It also checks that a minimum version is available or else loads a known version -- in this case, v1.3. It sends a boolean value to the callback (my widget) on whether or not jQuery was loaded in case there are any triggers needed to be made. And only after jQuery is loaded does it call my widget, passing jQuery into it.
See How to build a web widget (using jQuery) by Alex Marandon.
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
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");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else { // Other browsers
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($) {
// We can use jQuery 1.4.2 here
});
}
})(); // We call our anonymous function immediately
What if you also want to use some jQuery plugins? Is it safe to make yourself a single file with the minified versions of the plugins, and also load those, as below? (Loaded from S3, in this particular example.)
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
window.jQuery.getScript('http://mydomain.s3.amazonaws.com/assets/jquery-plugins.js', function() {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
});
}
};
document.documentElement.childNodes[0].appendChild(script)
}
})(window, document, "1.5.2", function($, jquery_loaded) {
// widget code goes here
});
SEE Can I use multiple versions of jQuery on the same page?
Can you use document.write() to optionally add the jQuery script to the page? That should force jQuery to load synchronously. Try this:
<script type="text/javascript" charset="utf-8">
// <![CDATA
if (typeof jQuery === 'undefined') {
document.write('<script src="{{ URL }}/jquery.js"><' + '/script>');
}
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>
If you want to do the jQuery check inside your widget script then I believe the following works cross-browser:
(function() {
function your_call($) {
// your widget code goes here
}
if (typeof jQuery !== 'undefined') your_call(jQuery);
else {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '{{ URL }}/jquery.js';
var onload = function() {
if (!script.readyState || script.readyState === "complete") your_call(jQuery);
}
if ("onreadystatechange" in script) script.onreadystatechange = onload;
else script.onload = onload;
head.appendChild(script);
}
})()
I know this is an old topic... but i got something faster that your hack.
Try in your widget
"init": function()
that will fix the trouble
I would download the jQuery source and modify the jQuery object to another (jQueryCustom).
And then find the instance that sets the $ symbol as a jQuery object and comment that routine.
I don't know how easy or difficult could that be, but I'd sure give it a try.
(Also, check your second option, as it is not bad, the site where the widget will be executing, might have a jQuery version older than the one you need).
EDIT: I just checked the source. You just have to replace jQuery with another string (jQcustom for example). Then, try commenting this line:
_$ = window.$
And you make reference to the custom jQuery like this:
jQcustom("#id").attr(...)