Unable to use jQuery with server-side Rails widget - javascript

I'm creating a widget, for which I have initialized jQuery like so:
# widget.js
(function() {
var jQuery;
var root_url = "<%= root_url%>";
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.9.1') {
var jquery_script = document.createElement('script');
jquery_script.type = "text/javascript";
jquery_script.asyc = true;
jquery_script.src = "http://code.jquery.com/jquery-1.9.1.js";
if (jquery_script.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else { // Other browsers
jquery_script.onload = scriptLoadHandler;
}
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(jquery_script, node);
} else {
jQuery = window.jQuery;
main();
}
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
function main() {
jQuery(document).ready(function($) {
// jQuery works great here!
// But not so much in rendered partials or in server-side JS actions
}
}
})();
If I make an ajax request to my server and respond with a JS action, I can't use jQuery in my action.js.erb file. It spits out the error $ is not a function.
Similarly, even rendering partials with jQuery scripts in them yields the same results.
I think I haven't set a global instance of jQuery, and if this is the case, I'm not sure how to do that. Perhaps I'm not supposed to?
How can I get around this problem?

This solution isn't what I was looking for but I was able to combine elements of the native JS widget with an iframe. Once I manipulate whatever elements I need to on the 3rd party site (as per my widget's functionality) I render a partial housing an iframe that lets me completely control the environment.

Related

Javascript file load fallback. Alternative to document.write()

You might be familiar with the good old Jquery load fallback:
<script>window.jQuery || document.write('<script src="https://example.com/jquery.js"></script>')</script>
But I read here and there: don’t use document.write, is bad for your health, it does not work on Chrome (It’s working for me, Chrome 78).
So I’m trying to replace it, but I’m not able to find a solution that will load synchronously the new js file, before DOM loaded is triggered.
And what ends happening with a DOM manipulation alternative is that the browser consideres the DOM is loaded and all $(document).ready() fail with “$ is not defined”.
function Jqfallback() {
var j = document.createElement('script');
j.src = 'https://example.com/jquery.js';
document.getElementsByTagName('head')[0].appendChild(j);
}
(window.jQuery || Jqfallback() );
No matter where I put this script, or the new JS file, which in this case ('head')[0] is already before all other JS which are in the body, it loads it “asyncronically”.
Is there another option or I continue rocking document.write() in late 2019?
It takes a bit of time to load and parse JQuery. So use a (small) timeout after appending the script.
This snippet wraps conditional loading in a immediately executed anonymous function:
(myScripting => {
if (!window.$) {
let j = document.createElement('script');
j.src = '//code.jquery.com/jquery-3.4.1.slim.min.js';
document.querySelector('head').appendChild(j);
setTimeout( myScripting, 200 );
} else {
myScripting();
}
})(JqIsLoadedSoMyScriptingCanStart);
// put your main scripting in here
function JqIsLoadedSoMyScriptingCanStart() {
// extra check
if (!window.$) {
alert("Sorry, JQuery is not loaded, can't continue");
return;
}
console.log("JQuery in place?");
console.log($("head script")[1]);
}
<script src="cantLoadThis"></script>
Place the code that uses jQuery in the onload() function.
var jQuery1 = document.createElement('script');
jQuery1.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";
jQuery1.onload = function () {
var $ = window.jQuery;
$.when(
$.getScript("https://someOtherScript.js"), //if you need
$.Deferred(function (deferred) {
$(deferred.resolve);
})
).done(function () {
console.log("all scripts loaded!!");
doNextTask(); //some other code which uses jQuery
});
};
Append jQuery to your document in onreadystatechange
document.onreadystatechange = function () {
if (document.readyState == "complete") {
// document is ready.
document.head.appendChild(jQuery1);
}
}

how to create a reusable javascript web-app from my HTML CSS and JS files

i have a working HTML file with CSS and JS files i want to create a web app with this.
i don't have any experience or idea how to create a webapp from what i have.
my code dosen't need any interaction with the server.
i have found this guide from this site
(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 {
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: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
1.) i understood till loading CSS but i did not get what the code is doing for loading a HTML file.
2.) is it possible to do a webapp with what i have and how..?
3.) i know css html js jq.......... is it important to know ajax or anything else for creating a web app.
thank you.
I'm not sure if I understand your question, but maybe if I try to describe what this script is doing, it will help you?
Basically, this script is (somewhat clumsily IMO) first loading jQuery, and then loading a stylesheet style.css and finally retrieving data from http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?. It assumes that you have a document element with the id "example-widget-container", which is where it will inject the html received from the JSON call.
If you clarify what exactly you're asking, then maybe I or someone else can help you some more.

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.

How to embed Javascript widget that depends on jQuery into an unknown environment

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(...)

Bookmarklet wait until Javascript is loaded

I've got a bookmarklet which loads jQuery and some other js libraries.
How do I:
Wait until the javascript library I'm using is available/loaded. If I try to use the script before it has finished loading, like using the $ function with jQuery before it's loaded, an undefined exception is thrown.
Insure that the bookmarklet I load won't be cached (without using a server header, or obviously, being that this is a javascript file: a metatag)
Is anyone aware if onload for dynamically added javascript works in IE? (to contradict this post)
What's the simplest solution, cleanest resolution to these issues?
It depends on how you are actually loading jQuery. If you are appending a script element to the page, you can use the same technique that jQuery uses to dynamically load a script.
EDIT: I did my homework and actually extracted a loadScript function from the jQuery code to use in your bookmarklet. It might actually be useful to many (including me).
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
// Usage:
// This code loads jQuery and executes some code when jQuery is loaded
loadScript("https://code.jquery.com/jquery-latest.js", function()
{
$('my_element').hide();
});
To answer your first question: Javascript is interpreted sequentially, so any following bookmarklet code will not execute until the library is loaded (assuming the library was interpreted successfully - no syntax errors).
To prevent the files from being cached, you can append a meaningless query string...
url = 'jquery.js?x=' + new Date().getTime();
I've paid an attention that in Chrome the order of scripts that are loaded is undetermined, when using #Vincent Robert's technique. In this case a little modification helps:
(function() {
var callback = function() {
// Do you work
};
// check for our library existence
if (typeof (MyLib) == 'undefined') {
var sources = [
'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js',
'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js',
'http://myhost.com/javascripts/mylib.min.js'];
var loadNextScript = function() {
if (sources.length > 0) {
var script = document.createElement('script');
script.src = sources.shift();
document.body.appendChild(script);
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done
&& (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
loadNextScript();
}
}
} else {
callback();
}
}
loadNextScript();
} else {
callback();
}
})();
I got a little closer with this, but not completely. It would be nice to have a discrete, example of a bookmarklet that demonstrated how to avoided caching.

Categories

Resources