loading jquery library from javascript getting error $ is not defined - javascript

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);

Related

load two jQuery if not loaded

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
}
}

Bootstrap's JavaScript requires jQuery While jQuery is already loaded

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.

Load jQuery dynamically and use it

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);

$.getScript gives Unexpected token

I found some code online that helps me to provide widgets to my clients. My understanding of the full code below is that it first detects if jQuery is present otherwise loads it. As part of my widget I also want to ensure that fancybox is loaded because I am basically providing a button that onClicks loads an iframe in fancybox.
The particular area of interest is in which .getScript gives me an error Unexpected token .. I know that jQuery is already loaded because .getJSON below works.
Code:
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5");
$.getScript(fancyboxScript);
/******* Load HTML *******/
var jsonp_url = widgetURL + "widgetCall.php?callback=?";
$.getJSON(jsonp_url,'merchantID='+merchantID, function(data) {
$('#widget-container').html(data.html);
});
The full code is below:
(function() {
// Localize jQuery variable
var jQuery;
var widgetURL = "http://...mywidgetURL/...";
/******** 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 {
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: widgetURL + "myCSS.css"
});
css_link.appendTo('head');
/******* Load FANCYBOX *******/
var fancy_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: widgetURL + "fancybox/source/jquery.fancybox.css?v=2.1.5",
media: "screen"
});
fancy_link.appendTo('head');
var fancy2_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: widgetURL + "fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7",
media: "screen"
});
fancy2_link.appendTo('head');
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5");
$.getScript(fancyboxScript);
/******* Load HTML *******/
var jsonp_url = widgetURL + "widgetCall.php?callback=?";
$.getJSON(jsonp_url,'merchantID='+merchantID, function(data) {
$('#widget-container').html(data.html);
});
});
}
})(); // We call our anonymous function immediately
you have made small mistake in your code
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5"); //closing round brackets is the issue
$.getScript(fancyboxScript);
you have added a closing round brackets in the line above, hence the syntax error, just remove it and try, it should work as you intended.
Happy Coding:)
well this must be one of the stupidest mistakes on SO. But I hope it saves someone some time in future.
Basically I had an additional ) at the end of my fancyboxScript declaration.
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5");
should have just been
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5";

Trying to build a widget using jquery and javascript

I'm currently working on a widget using javascript and jquery. Now what I want to create a widget button that when clicked, will start a chat with the person whose id is associated with the widget. On the main website it's just a call to the function that does that but with the widget I don't really know how to do it since I can't call my function from another website.
I've read a few tutorials on creating jquery widgets but I didn't fully grasp them because it seems that what the tutorial was teaching was to retrieve data from the host server which isn't really my intention. Also they quoted the use of JSON which I don't also fully grasp as it seems that JSON is a way of displaying objects and strings.
Anyway I need some guidance on how to achieve this.
So far this is what I put down :
(function () {
var jQuery;
if (window.jQuery == undefined || window.jQuery.fn.jquery !== '1.8.1') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
jQuery = window.jQuery;
main();
}
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
function main() {
jQuery(document).ready(function ($) {
var homeURL = 'http://www.reflap.com/';
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: homeURL + "assets/widget.css"
});
var $container = ('#mywebsite-container');
css_link.appendTo('head');
$.getJSON(homeURL + 'assets/js/anonymous.js', function (response) {
$container.append(response.html);
});
});
}
})();
NEW EDIT
This is what I attempted before.
The function in question is call chat and it takes 3 parameters.
So my first widget looked like this
<script src="http://www.mydomain.com/chatter.js"></script><a href="#"
onclick="Chatter.chat('1','user', null)" id="chat-widget">Chat now</a>
But that doesn't work.

Categories

Resources