I'm building a widget for users to add on their websites to chat with people from their website. Now since the script that handles it needs jquery installed I have been attempting to add the jquery source directly in the javascript file to no avail. It just seems that it's not working. I tried this
(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 () { // 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();
}
function main(){
$(document).ready(function($){
$('.reflap-call').click(function(){
window.location.href = 'http://www.reflap.com/beta/widget/michael';
});
});
}
})();
But when I go on any website and add this script
<script src="http://www.reflap.com/beta/assets/js/widget.js"></script>
Chat
The script doesn't work because it seems that the jquery is not properly loaded. The only way I can circumvent it is by using this script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="http://www.reflap.com/beta/assets/js/widget.js"></script>
Chat
I would like to properly add jquery to the widget.js so I won't have to add a third line when users want to use the script.
Although you can (manually load jQuery) from within your widget, it is better to just add the jQuery tag, or ask your widget users to add it.
I got it to work just by commenting out
jQuery = window.jQuery.noConflict(true);
Related
I am aware that in Internet Explorer (Pre-IE9) you cannot use document.addEventListener(), instead you must use document.attachEvent. The problem I'm having is that document.attachEvent('onload', AddExternals); does nothing, at all. In the console, the output should be as follows:
- document.attachEvent
- Adding Externals...
- jQuery loaded!
However in IE8, the console output is:
Is there any obvious reason why this would occur in the below code?
if (document.addEventListener) {
console.log("document.addEventListener")
document.addEventListener("DOMContentLoaded", AddExternals);
} else if (document.attachEvent) {
console.log("document.attachEvent")
document.attachEvent("onload", AddExternals);
}
function AddExternals(){
console.log("Adding Externals...");
var jq = document.createElement("script");
jq.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(jq);
jq.onload = function(){console.log("jQuery loaded!")};
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
}
Edit
I have changed document.attachEvent("onload", AddExternals) and now the console is outputting both document.attachEvent and Adding Externals... but the function never completes?
As far as I know, there is no document.onload event. Instead, you would use window.onload as your fallback. You may also have to test the document state to make sure that it is not already loaded (e.g. the events have already fired).
For a completely tested function to know when the document is ready in any level of browser see the code in this prior question/answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
Keep in mind that older versions of IE do not have a .onload for your script tag so you will not necessarily see that console message, but your script should still load. There is a more complicated scheme that will get you notified of when it is loaded for older versions of IE here: javascript notify when script is loaded dynamically in IE
I would suggest you change your script to this:
function AddExternals(){
var doneLoad = false;
function onload() {
if (!doneLoad) {
doneLoad = true;
console.log("jQuery loaded!")
}
}
console.log("Adding Externals...");
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.onload = doneLoad;
jq.onreadystatechange= function () {
if (script.readyState == "loaded" || script.readyState == "complete"){
doneLoad();
}
};
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
}
Relevant changes:
Added support for older method of knowing when the script has loaded.
Made sure there is no duplicate load notification since listening for multiple mechanisms
Set .src before inserting the script tag.
I just want to inject jQuery into a webpage from a safari extension. But only to some pages because adding jQuery as a start-/endscript would inject it to all pages and this makes browsing slow.
I tried it by creating a script tag using its onload function:
var node = document.createElement('script');
node.onload = function(){
initjquerycheck(function($) {
dosomethingusingjQuery($);
});
};
node.async = "async";
node.type = "text/javascript";
node.src = "https://code.jquery.com/jquery-2.0.3.min.js";
document.getElementsByTagName('head')[0].appendChild(node);
to check if jquery is loaded i use:
initjquerycheck: function(callback) {
if(typeof(jQuery) != 'undefined'){
callback(jQuery);
}else {
window.setTimeout(function() { initjquerycheck(callback); }, 100);
}
}
But typeof(jQuery) remains undefined. (checked that using console.log()).
Only if I call console.log(typeof(jQuery)) from the debugging console it returns 'function'. Any ideas how to fix that? Thanks in advance!
Extension injected scripts cannot access the web page's JavaScript namespace. Your injected script creates a <script> element and adds it to the page's DOM, but then the jQuery object instantiated by the script belongs to the page's namespace, not to your injected script's.
There are at least two potential solutions. One, inject jQuery into the page the normal way, using the extension API. This method is only viable if the web pages that you are targeting can be categorized using URL patterns.
Two, use Window.postMessage to communicate between your injected script and the web page's namespace. You will need to add another <script> to the page, and in this script, have a listener for the message event. The listener will be able to use jQuery as if it were "native" to the page itself.
Here's some code to get you started, if needed.
In the extension injected script:
var s0 = document.createElement('script');
s0.type = 'text/javascript';
s0.src = 'https://code.jquery.com/jquery-2.0.3.min.js';
document.head.appendChild(s0);
var s1 = document.createElement('script');
s1.type = 'text/javascript';
s1.src = safari.extension.baseURI + 'bridge.js';
document.head.appendChild(s1);
window.addEventListener('message', function (e) {
if (e.origin != window.location.origin)
return;
console.log(e.data);
}, false);
window.postMessage('What jQuery version?', window.location.origin);
In bridge.js:
window.addEventListener('message', function (e) {
if (e.origin != window.location.origin)
return;
if (e.data == 'What jQuery version?') {
e.source.postMessage('Version ' + $.fn.jquery, window.location.origin);
}
}, false);
On my page I need to make a dynamic script with src=some_external_path element.
That script element donwloads some JS inside of itself and that JS intern needs to be executed in order to pull some image content.
My problem is that it needs some time to complete JS execution inside that script element, how is it achievable?
It works if I insert alert by the end of the script or run some awkward for loop, unfortunately it doesn't work with setTimeOut function.
Here is sample code:
var s = document.createElement('script');
s.setAttribute("src", "some_external_path");
document.getElementById('test').appendChild(s);
// if i replace that alert - doesn't work, it seems page needs some delay
alert(document.getElementById('test').text);
I also tried something like:
setTimeout(function(scriptElement){
document.getElementById('test').appendChild(scriptElement);
}, 5000, s);
And it didn't work either, I also have thought of executing code inside that script element but it doesn't seem to work because of security restrictions(script.text or script.innerHTML return blank string);
Can you suggest anything to make this code complete transaction without loops and hopefully self-made delays ?
http://api.jquery.com/jQuery.getScript/
If you do not want to use jQuery, just look it up how it is done and inspire from it.
This should do it (without using jQuery when you don't need to):
var loadScript = function(url, cb){
var s = document.createElement("script"), done = false;
s.setAttribute("src", url);
s.onreadystatechange = s.onload = function(){
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
cb();
}
};
document.getElementsByTagName("head")[0].appendChild(s);
}
And you call it like so:
loadScript("http://path.to.my/script.js", function(){
alert("YAY its loaded");
});
I hope that helps.
I'm loading a few YUI scripts dynamically in my code in response to an Ajax request. The DOM and the page is fully loaded when the request is made - it's a response for an user event.
I add the <scripts> tag to head as children, but I stumbled in a few problems:
I add two YUI scripts hosted at the Yahoo! CDN and an inlined script of my own responsible for creating object, adding event listeners and rendering the YUI widgets. But I when my script run the YUI scripts are not loaded yet giving me errors and not running as I expect.
There's a way to only run my script (or define a function to be run) when YUI scripts are fully loaded?
Have you tried an onload event?
Edited:(thanks Jamie)
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
//IE:
if(window.attachEvent && document.all) {
script.onreadystatechange = function () {
if(this.readyState === "complete") {
callback_function(); //execute
}
};
}
//other browsers:
else {
script.onload = callback_function; //execute
}
document.getElementsByTagName("head")[0].appendChild(script);
If you're using YUI 2.x I highly recommend using the YUI Get utility, as it's designed to handle just this sort of a problem.
If you are loading multiple individual script files from the Yahoo! CDN, you'll need to makes sure both are loaded before executing your dependent code. You can avoid this using the combo handler. See the Configurator to get what the script url should be to load both/all needed YUI files from one url.
http://developer.yahoo.com/yui/articles/hosting/
With that in mind, assuming you must load the YUI files asynchronously, you should use an onload/onreadystatechange handler as noted by digitalFresh.
I would recommend the following pattern, however:
(function (d) {
var s = d.createElement('script'),
onEvent = ('onreadystatechange' in s) ? 'onreadystatechange' : 'onload';
s[onEvent] = function () {
if (("loaded,complete").indexOf(this.readyState || "loaded") > -1) {
s[onEvent] = null;
// Call your code here
YAHOO.util.Dom.get('x').innerHTML = "Loaded";
}
};
// Set the src to the combo script url, e.g.
s.src = "http://yui.yahooapis.com/combo?2.8.1/...";
d.getElementsByTagName('head')[0].appendChild(s);
})(document);
You could use a setTimeout() to run some function that just checks if it's loaded - check something like
if (typeof YUI_NAMESPACED_THING !== "undefined") runCode()
EDIT Thanks, CMS
If I understand this correctly, your ajax response with this:
<script href="yui-combo?1"></script>
<script href="yui-combo?2"></script>
<p>some text here</a>
<script>
// using some of the components included in the previous combos
// YAHOO.whatever here...
</script>
If this is the case, this is a clear case in which you should use dispatcher plugin. Dispatcher will emulate the browser loading process for AJAX responses. Basically it will load and execute every script in the exact order.
Best Regards,
Caridy
I'd like to inject jQuery into a page using the Google AJAX Libraries API, I've come up with the following solution:
http://my-domain.com/inject-jquery.js:
;((function(){
// Call this function once jQuery is available
var func = function() {
jQuery("body").prepend('<div>jQuery Rocks!</div>');
};
// Detect if page is already using jQuery
if (!window.jQuery) {
var done = false;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement("script");
script.src = "http://www.google.com/jsapi";
script.onload = script.onreadystatechange = function(){
// Once Google AJAX Libraries API is loaded ...
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
// ... load jQuery ...
window.google.load("jquery", "1", {callback:function(){
jQuery.noConflict();
// ... jQuery available, fire function.
func();
}});
// Prevent IE memory leaking
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
}
// Load Google AJAX Libraries API
head.appendChild(script);
// Page already using jQuery, fire function
} else {
func();
}
})());
The script would then be included in a page on a separate domain:
http://some-other-domain.com/page.html:
<html>
<head>
<title>This is my page</title>
</head>
<body>
<h1>This is my page.</h1>
<script src="http://my-domain.com/inject-jquery.js"></script>
</body>
</html>
In Firefox 3 I get the following error:
Module: 'jquery' must be loaded before DOM onLoad! jsapi (line 16)
The error appears to be specific to the Google AJAX Libraries API, as I've seen others use a jQuery bookmarklet to inject jQuery into the current page. My question:
Is there a method for injecting the Google AJAX Libraries API / jQuery into a page regardless of the onload/onready state?
If you're injecting, it's probably easier to request the script without using the google loader:
(function() {
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
script.onload = script.onreadystatechange = function(){ /* your callback here */ };
document.body.appendChild( script );
})()
I found this post after we figured out a different solution. So for some reason, if you can't use the accepted solution, this one seem to work fine:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
// jQuery hasn't been loaded... so let's write it into the head immediately.
document.write('<script type="text/javascript" src="/jquery-1.3.2.min.js"><\/script>')
}
</script>
One issue with the accepted solution is that you're forced to put all your code that you want to run on the page into your callback function. So anything that needs jQuery (like plugins) need to be called from that function. AND, all your other included JS files that require jQuery are dependent upon jQuery being loaded BEFORE all the other scripts fire.
I Got It Working!!!!! I figured it out by looking in the application playground....
Here is the wrapper to start using jquery.... Put an alert in the function to see it work
google.load("jquery", "1.4.2");
function OnLoad(){
$(function(){
});
}
google.setOnLoadCallback(OnLoad);
You can use less painful solution to inject jquery (the lastest stable version available) to any page.
jQuerify - Chrome extension used to inject jQuery (the latest stable version available) into any web page (even HTTPS)"