Loading jQuery in a blogger post causes it to freeze - javascript

I've created some code which people can copy and paste into their websites, and it should work in blogspot. This code requires jQuery and the jCarousel plugin. I use
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
to load jQuery before running my javascript code. The issue is that some blogger templates load jQuery already, and then running the above code causes the blog post to never load (it just stays on the loading screen).
I could load it using javascript after if (typeof jQuery == "undefined") but for the jCarousel plugin to work jQuery must be loaded first, so this causes the post to load but the carousel to break.
Anybody know any solutions?

Can't you check for the existence of jQuery and still load jCarousel after that?
<script type="text/javascript">
if (typeof jQuery === "undefined") {
document.write('<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"><\/script>');
}
</script>
<script src="http://path/to/jcarousel" type="text/javascript"></script>
On second thought, I am not convinced this will always work. I don't think this guarantees that jQuery will load before jCarousel. I came up with an alternate solution that seems to be more robust. It makes sure that jQuery is loaded, and then uses jQuery to load the library using $.getScript(). Then your code is called from the callback of getScript. This ensures that everything happens in the proper order:
<script type="text/javascript">
if (typeof jQuery !== "undefined") {
loadLibs();
} else {
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery.js';
document.getElementsByTagName('head')[0].appendChild(script);
var timeout = 100; // 100x100ms = 10 seconds
var interval = setInterval(function() {
timeout--;
if (window.jQuery) {
clearInterval(interval);
loadLibs();
} else if (timeout <= 0) {
// jQuery failed to load
clearInterval(interval);
}
}, 100);
}
function loadLibs() {
$.getScript("http://sorgalla.com/projects/jcarousel/lib/jquery.jcarousel.min.js", function(data, textStatus, jqxhr) {
myCode();
});
}
function myCode() {
$(document).ready(function() {
$('#mycarousel').jcarousel();
});
}
</script>
Demo: http://jsfiddle.net/jtbowden/Y84hA/2/
(Change the Framework in the left column to any version of jQuery, or some other library. It should always load the carousel correctly)
Edit:
This version is similar, but uses a <head> load for the lib, just like for jQuery. It is faster than $.getScript():
http://jsfiddle.net/jtbowden/y8nGJ/1/

Related

detect jquery version use on or live

I am writing a plugin which can be used in any website where I dont know the exact version of jquery and getting a few issues with the .on() method.
To fix it I have something simple like this but still getting errors in jQuery 1.4.2.
var $myElements = $('.elements'),
myFunction = function(e){
console.log('here');
e.preventDefault();
}
if (typeof jQuery != 'undefined') {
if(jQuery.fn.jquery < 1.4){
$myElements.live('click', myFunction);
} else {
$(document).on('click', $myElements, myFunction);
}
}
Based on the previous answer, you can do this too:
;(function($) {
if(!$.fn.on) {
$.fn.on = $.fn.live;
}
}(window.jQuery || window.Zepto));
Then you can use on in the rest of your code.
You should bundle your own version of jQuery to save yourself a lot of hassle and a lot of redundant code. You can do this using noConflict to ensure that both your code and the code of the source website act independently:
<!-- load your jQuery -->
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
var yourjQueryVersion = $.noConflict(true);
(function($) {
// Now you can use $ just like you normally would
// And it will only execute against jquery-1.11.0
$(function() {
var $myElements = $('.elements'),
myFunction = function(e){
console.log('here');
e.preventDefault();
}
$(document).on('click', $myElements, myFunction); // Yay!
});
})(yourjQueryVersion);
</script>
This means that:
You don't need to write extra code for all jQuery version differences
If the target website upgrades to jQuery 2.0 (or similar), none of your code will break.
The source website might even be using a CDN, so there is a good chance only one copy of the jQuery library may be loaded due to caching.

Dynamically load jquery

I'm working in a really twisted environment in which I cannot handle this problem through the view logic of the MVC framework I'm using (Cakephp). It could happen because I have to load this piece of code inside a page which already has a jQuery script loaded in.
If I simply load jQuery in my piece of code, it works as long as there's no other jQuery scripts present. When there are 2 scripts, it doesn't work and says $ is not a function. Not really sure how this works but explanations could help.
Anyway I've got to the point of dynamically loading the script into the page.
So this is my code:
<script id="loadjq" type="text/javascript"></script>
<script id="loadcloud" type="text/javascript"></script>
<script type="text/javascript">
if(typeof jQuery=="undefined"){
document.getElementById('loadjq').src= 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
}
document.getElementById('loadcloud').src= '/js/jqcloud.js';
$(document).ready(function(){
$("#tagcloud").jQCloud(word_list,{});
});
</script>
This loads the script but when I try to load jqcloud.js, it can't find the other script, probably because it runs before the other script is loaded. With a few dirty tricks I could go through that, but the same problem happens when i reach $(document).ready(function()
Is there a clean way to do this? I need it to wait for the previous scripts to be loaded before executing, or at least, that's what the problem looks like. Not really sure if this is really my problem.
How about setting event handlers on the jquery script element to call the jqcloud script on load completion. Something like
if(typeof jQuery=="undefined"){
var loadjqScript = document.getElementById('loadjq').src =
'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
// Code below handles browser that support script onload
// and ones that don't
var loadFunction = function()
{
if (this.readyState == 'complete' || this.readyState == 'loaded') {
loadJqCloud();
}
};
loadjqScript.onreadystatechange = loadFunction;
loadjqScript.onload = loadJqCloud;
}
function loadJqCloud() {
document.getElementById('loadcloud').src= '/js/jqcloud.js'
}

jQuery on the bottom, wait execution script on <head> until it is loaded

I saw similar question here in SO, where someone wants to do the same thing. The different case is that I have this lightweight script that listens for event bubbling to the top of the document root that I intentionally want to put on the top of the page and I dont want to wrap it inside $(document).ready(). It looks something like this:
<html>
<head>
<script>
document.documentElement.onclick = function (e) {
//$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
}
</script>
</head>
And then near the bottom of the page I include jQuery like this:
<body>
<script src="./jQuery.js"></script>
</body>
</html>
As you can see on the <head> when I'm making an ajax call to somewhere using $.ajax, it's possible that jQuery is not yet loaded, so that it may throw $ is undefined error when someone clicks on something on DOM, and jQuery is not loaded yet. My workaround is probably to use settimeout hoping that jquery will be loaded sometime later and the code is working like this:
if (typeof $ === 'undefined'){
setTimeout(doAJAXJquery, 50);
}else{
$.ajax(//blablabla) //jQuery loaded and ready to use!!
}
But it's a really dirty hack. How am I supposed to know when jQuery is finished loading? that 50ms i put there is only an arbitrary value i made up myself. Of course it is still not gonna work if jquery hasn;t been loaded yet and it already passes 50ms.
Is there any better workaround so when jQuery is undefined, it is gonna retry sometime later again, or put a function that executes ajax inside some callback that gets executed when jQuery is ready? thanks.
what about
<head>
<script type="text/javascript">
var init = function(){
document.documentElement.onclick = function (e) {
//$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
}
}
</script>
</head>
<body>
<script src="./jQuery.js"></script>
<script type="text/javascript">
init();
</script>
</body>
If you want to execute the list of functions (or events 'fired') waiting for jQuery to load you could create your own 'ready' function :))
var runList = new Array(), timer = setInterval(function(){
if (typeof(jQuery) != 'undefined')
{
clearInterval(timer);
if (runList.length>0) for(var i in runList) runList[i]();
}
}, 50);
runList.push(function(){alert(1);});
runList.push(function(){alert(2);});
var jQuery = 1;

google.load not working when run in jquery's $(window).load(function(){});?

I'm using the Google AJAX Feed API to search for a RSS feed. It works when I just run the javascript in the head of my HTML document in EXAMPLE 1 below (I know I'm getting no result, but that's a problem for another day!), but I need to actually run it when everything's loaded. I'm using jquery, so I've got a $(window).load(function(){}); method, but it doesn't work when I run the Google code in there (EXAMPLE 2). Can anyone see what I'm doing wrong?
EXAMPLE 1 - index.html
<head>
<script type="text/javascript">
console.debug("before google load code");
google.load("feeds", "1");
console.debug("after google load code");
google.setOnLoadCallback(loaded);
function loaded() {
console.debug("google loaded");
google.feeds.findFeeds("news", feedSearchDone);
}
function feedSearchDone(result) {
if (result.error || result.entries.length <= 0) {
console.debug("No Results Found");
return;
}
else {
console.debug(result.entries[0].url);
} }
</script>
</head>
EXAMPLE 1 - code.js
$(window).load(function() {
console.debug("in jquery load function");
});
EXAMPLE 1 - output in Firebug:
before google load code
after google load code
in jquery load function
google loaded
No Results Found
EXAMPLE 2 - code.js
$(window).load(function() {
console.debug("in jquery load function");
console.debug("before google load code");
google.load("feeds", "1");
console.debug("after google load code");
google.setOnLoadCallback(loaded);
function loaded() {
console.debug("google loaded");
google.feeds.findFeeds("news", feedSearchDone);
}
function feedSearchDone(result) {
if (result.error || result.entries.length <= 0) {
console.debug("No Results Found");
return;
}
else {
console.debug(result.entries[0].url);
} }
});
EXAMPLE 2 - output in Firebug
in jquery load function
before google load code
window.loadFirebugConsole is not a function
[Break on this error] <html lang="en">
Even though the error refers to Firebug, I don't think that's the cause because it the page behaves the same (no elements are on the screen) when I view it in Safari. Thanks for reading.
The JQuery onload can ONLY be used after the google onLoad callback.
function initialize() {
$(function () {
// Some other code here
});
}
google.setOnLoadCallback(initialize);
Try adding that to the code.js file.
You have to use $(document).ready instead, the scripts will only load after the DOMLoad completes.
Are you definitely including jquery above your $ doc.ready?
In stead of using google.load the google Libraries API states:
The preferred method is to load the libraries via standard tags (as in <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>, which will result in the fastest loads.
The nice thing about this is that you don't need to set google.setOnLoadCallback and the libraries are available at page load anyway.

Testing if jQueryUI has loaded

I'm trying to debug a website, and I think that jQueryUI may not have loaded properly. How can I test if jQueryUI has loaded?
if (jQuery.ui) {
// UI loaded
}
OR
if (typeof jQuery.ui != 'undefined') {
// UI loaded
}
Should do the trick
You need to check if both, the jQuery UI Library file and CSS Theme are being loaded.
jQuery UI creates properties on the jQuery object, you could check:
jQuery.ui
jQuery.ui.version
To check if the necessary CSS file(s) are loaded, I would recommend you to use Firebug, and look for the theme files on the CSS tab.
I've seen problems before, when users load correctly the jQuery UI library but the CSS theme is missing.
I know this is an old question, but here is a quick little script you can use to wrap all your jQuery UI things that don't have an associated event to make sure they get executed only after jQuery UI is loaded:
function checkJqueryUI() {
if (typeof jQuery.ui != 'undefined') {
do_jqueryui();
}
else {
window.setTimeout( checkJqueryUI, 50 );
}
}
// Put all your jQuery UI stuff in this function
function do_jqueryui() {
// Example:
$( "#yourId" ).dialog();
}
checkJqueryUI();
Just test for the ui object, e.g.
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function(){
// did the UI load?
console.log(jQuery.ui);
});
</script>
You can check if jQuery UI is loaded or not by many ways such as:
if (typeof jQuery.ui == 'undefined') {
// jQuery UI IS NOT loaded, do stuff here.
}
OR
if (typeof jQuery.ui != 'function') {
// jQuery UI IS NOT loaded, do stuff here.
}
OR
if (jQuery.ui) {
// This will throw an error in STRICT MODE if jQuery UI is not loaded, so don't use if using strict mode
alert("jquery UI is loaded");
} else {
alert("Not loaded");
}
Well, you are using jQuery to check for the presence of jQuery. If jQuery isn't loaded then $() won't even run at all and your callback won't execute, unless you're using another library and that library happens to share the same $() syntax.
window.onload = function(){
if(window.jQuery){
if(window.jQuery.ui){
}else{
console.log("jquery ui isn't loaded");
}
}else{
console.log("jquery isn't loaded");
}
}

Categories

Resources