how to generate headJS fallbacks - javascript

How can I properly implement fallback for headJS and Jquery (if the CDN fails to load) within the head load function?
I cant find anything on the documentation about fallbacks.
http://headjs.com/
My code is the following: (right now HeadJS and Jquery are loaded from CDN)
<script src="//cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.min.js"></script>
<script>
// this loads jquery asyncrounously & in parallel
head.load("//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js", "script1", "script2");
if (head.screen.innerHeight < 800) {
/* code specific to VIEWPORT < 800 */
head.load("{T_THEME_PATH}/footable/js/footable.min.js");
head.ready(function () {
// some callback stuff
$('.footable').footable();
});
}
</script>

Here the answer wit headJS. run a test and fallback to something else like this
head.load({"jquery": "...path to cdn"});
and then
head.ready("jquery", function() {
if (!window.jQuery) {
head.load({"jquery": "...path to fallback"});
}
});

Related

Javascript Conflict with PHP

I am not sure what is causing the issue with my mobile menu system here.
I have two pages with an identical function to condense the nav systems into a mobile menu (below)
<script type="text/javascript">
$(document).ready(function() {
$('.main_nav nav ul').clone().appendTo('.top_menu');
$('.sec_nav nav ul').clone().appendTo('.top_menu');
$('.bottom-links ul').clone().appendTo('.top_menu');
$('.footer-links ul').clone().appendTo('.top_menu');
$('.rfi_nav').clone().appendTo('.m_form');
// For Menu-----------------
$('.menu, .m_close, .rfi_nav label.title').click(function(e) {
$('body').toggleClass('m_open');
});
// For Menu On window resize------------------
function checkwindowSize() {
var windowSize = $(window).width();
if(windowSize > 320 && windowSize < 1023) {
//$('body').toggleClass('open');
}
else{
$('body').removeClass('m_open');
}
}
checkwindowSize();
$(window).resize(function(){ checkwindowSize() });
// For BT Select DropDown-----------------
$('select').selectpicker();
// For content Scroll bar-----------------
(function($){
$(window).load(function(){
$(".scroll").mCustomScrollbar({
scrollButtons:{enable:true,scrollType:"continuous",scrollSpeed:40,scrollAmount:40},
advanced:{updateOnBrowserResize:true, updateOnContentResize:true, autoExpandHorizontalScroll:true, autoScrollOnFocus:true }
});
});
})(jQuery);
// BT Accordian------------
function toggleChevron(e) {
$(e.target)
.prev('.panel-heading')
.find("i.indicator")
.toggleClass('glyphicon-plus glyphicon-minus');
}
$('#accordion').on('hidden.bs.collapse', toggleChevron);
$('#accordion').on('shown.bs.collapse', toggleChevron);
});
</script>
My script works perfectly on my homepage (http://dev.oru.edu) but my internal pages (http://dev.oru.edu/generic-hf.php and http://dev.oru.edu/generic-hfs.php) seem to be conflicting somewhere and I cannot detect where or why.
Can someone please help me identify what is causing the conflict resulting in my mobile menus not loading? I am not familiar with JavaScript so I am fumbling around and don't want to mess the code up from the original developer since it is still working on the homepage.
The furthest I have been able to detect is that the problem is not restricted to only mobile devices but desktop browsers as well when scaled to mobile sizes. At first I thought it may be relevant to the device type but the issue is persistent with the desktop browsers as well.
Looking at the error console is very telling:
Many of your scripts depend on JQuery being loaded before they run. You're loading JQuery, but doing it asynchronously:
<script async type="text/javascript" src="js/1.11.3.jquery.min.js"></script>
Your scripts are then immediately calling window.$ and window.jQuery which haven't been loaded yet.
Remove the async attribute and it should work.
I had an "async" on my primary jquery library which was causing the function to not load the library properly.

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.

Run/load function when there is a form on the page

The following script link, is linking to a JavaScript file that handle form validation
<script type="text/javascript" src="assets/js/form-validation.js"></script>
And it is included to all the pages using PHP include, the question is; how do I only make it run or even load when there is a form on the page?
I tried this: $('form').load('form-validation.js', function(){ /* callback */ });
But did not work, I also searched and did not find a real answer...
You should use jQuery.getScript(), it load a JavaScript file from the server using a GET HTTP request, then execute it.
You can use .length property to check form exists or not.
if ($('form').length) {
$.getScript('form-validation.js', function () {
/* callback */
});
}
EDIT
There is no option to add it to the JS file it self, and make it work
//Place this code at the top of your form-validation.js file
$(document).ready(function () {
if ($('form').length > 0) {
//Do validation
}
});
use jquery to do it :
<script type="text/javascript">
$(document).ready(function(){
if ($('form').length>0) {
$.getScript('form-validation.js', function () {
});
}});
</script>

jquery page resize not working

Hey guys I'm just starting out with JQuery so I'm an utter noob, but I've been following the codecademy tutorial and am trying to implement a page resize function to fit into a resized browser. However nothing is working inside the script tags with jquery inside - even alerts aren't happening. The first script runs fine and says hi, but neither of the other two alerts work, nor any of the Jquery stuff. I'm not sure if it makes a difference, but there are two soundcloud widgets on the page as well, one which is a programmable widget.
<script type="text/javascript">alert("Hi");</script>
<script type="text/javascript">
alert("Hello");
$(document).ready(function() {
alert("Jquery");
$(window).resize(function() {
if ($(window).width() < 1020) {
$('#page').css("width", "500px");
}
)};
});
</script>
Apart from figuring out why nothing happens, I'd also like to know if this resize thing works.
You got syntax error : window.resize should close with }); not )};
And be sure you called jQuery first.
By the way : why don't you simply use Media Queries ?
#media screen and (max-width: 1020px) {
#page {
width: 500px;
}
}
Without seeing the head section of your page, it sounds like you do not have the jquery library loaded. You must include a reference to the library, you can download it to your server of reference it by including <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> on your page (before any calls to $)
If your script isn't doing anything, almost certainly you have a syntax error somewhere within your <script> tag that is causing the code to be invalid and fail to run.
In this situation, your problem is that you haven't closed your resize call / function parameter properly:
$(window).resize(function() {
if ($(window).width() < 1020) {
$('#page').css("width", "500px");
}
)};
should be
$(window).resize(function() {
if ($(window).width() < 1020) {
$('#page').css("width", "500px");
}
});
Note that the parentheses and curly braces at the end of the function must be closed in exactly the opposite order as they were opened at the start.
If you are sure that you have included the jquery library
*try this code:*
<script>
$(function () {
var oldY = document.documentElement.clientWidth;
if (oldY <= 1020) {
$('#page').css({'width', '500px'});
}
});
</script>
First correct the syntax by changing )} into }). Than make sure you are including the jquery.js file before using jQuery code. Something like:
<html><head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>//jQuery Code here</script>
</head>
<body>
<script>//jQuery Code here</script>
</body></html>
Maybe open the console and check the javascript error messages (i.e. Ctrl + Shift + I in Chrome/Firefox others might be different). Also enter $ === jQuery into the console and see to which it is evaluated (should be true if jQuery is bound to $).
It is a common shortcut in jQuery to use $( function() { ... } )); for document.ready see jQuery API
If you are using other JavaScript libs that might overwrite the $ use
jQuery( document ).ready(function( $ ) {
// Code using $ as usual goes here.
});
to ensure $ is bound to jQuery.

Loading jQuery in a blogger post causes it to freeze

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/

Categories

Resources