Run after jQuery version selection is done - javascript

I'm trying to find out if a user supports jQuery 2.xThis works fine, but when I try to run a script it doesn't work because jQuery isn't done loading...
How can I trigger __run() after jQuery is done loading.
Init script:
function __run(){
//
// function runs the jQuery website
//
$("body").append( "<p>Test</p>" );
}
(function () {
var s, s0, js;
if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
js = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
} else {
js = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
alert('Woow, that\'s one old browser, maybe you should upgrade. We don\'t support this version, you can try to use the website though');
}
s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = js;
s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(s, s0);
__run();
}());

Try this
(function () {
var s, s0, js;
if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
js = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
} else {
js = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
alert('Woow, that\'s one old browser, maybe you should upgrade. We don\'t support this version, you can try to use the website though');
}
s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = js;
s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(s, s0);
s.onreadystatechange= function () {
if (this.readyState == 'complete') __run();
}
s.onload= __run;
}());

Check with onreadystatechange
s.onload = s.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
__run();
}
};

Related

Load scripts if not already loaded, and then use them

I have 4 javascript libraries I would like to load if the are not already loaded. Then, I want to use their functions.
My problem is that I am getting Uncaught ReferenceError: sbjs is not defined, the scripts get loaded but I can't actually use them.
I have it working perfectly to where it will add the scripts above the </body> tag if they are not already loaded, but I can't seem to get them to work.
Here is my code:
<script>
window.onload = myapp_scripts;
function myapp_scripts () {
var myapp_script;
if (!window.jQuery) {
myapp_script = document.createElement('script');
document.body.appendChild(myapp_script);
myapp_script.src = 'http://myapp.dev/js/jquery.min.js';
console.log('load jquery');
}
if (!window.Cookies) {
myapp_script = document.createElement('script');
document.body.appendChild(myapp_script);
myapp_script.src = 'http://myapp.dev/js/cookie.min.js';
console.log('load cookies');
}
if (typeof url == 'undefined') {
myapp_script = document.createElement('script');
document.body.appendChild(myapp_script);
myapp_script.src = 'http://myapp.dev/js/url.min.js';
console.log('load url');
}
if (typeof sbjs == 'undefined') {
myapp_script = document.createElement('script');
document.body.appendChild(myapp_script);
myapp_script.src = 'http://myapp.dev/js/sourcebuster.min.js';
console.log('load sbjs');
}
myapp_init();
}
function myapp_init () {
sbjs.init();
console.log(Cookies.get('source_id'));
console.log(url('source_id'));
console.log(sbjs.get.current);
$('#myapp_form').submit(function (event) {
event.preventDefault();
console.log('form submitted');
});
}
</script>
How do I make it so I can also use the scripts I've loaded dynamically?
I think your problem is because myapp_init() is executed before scripts are loaded
You need to manage script load event and after call myapp_init()
some like this inside each if() condition:
var myapp_script;
var scripts_loaded = 0;
if (!window.jQuery) {
myapp_script = document.createElement('script');
document.body.appendChild(myapp_script);
myapp_script.src = 'http://myapp.dev/js/jquery.min.js';
console.log('load jquery');
myapp_script.onload = function(){
scripts_loaded ++;
if(scripts_loaded === 4){ //4 because in your example you have 4 scripts to load
myapp_init();
}
}
}else{
scripts_loaded ++;
}
//...
//And so on with others if conditions
Is not a elegant solution but is only one the idea: to check in some way if all scripts are loaded and after that call myapp_init();

Set response data from external JS script

I have this script
<script>
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('/script/script.js', function() {
// put your code here to run after script is loaded
});
</script>
And I can't figure out how can I get response data from the script I'm trying to load.
Basically, this script contains a function that does something and then returns some value.
I know that in jQuery analog in would be just data argument in getScript function, but I only have native JS here.
What and where should I add to get response data in my script?
Assuming that your script contains a function declared in a global scope, you can simply include this script and then execute any function / access any member from this script:
After your script has been loaded and executed, you can work with it just like with a simple script which is a part of your current document.
Here is a demo which loads jQuery script from Google CDN and then outputs jQuery version (which is a part of jQuery library):
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
console.log("typeof jQuery: " + typeof jQuery); // jQuery not loaded
loadJS("https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js", function() {
console.log("typeof jQuery: " + typeof jQuery + ", version = " + jQuery.fn.jquery); // jQuery has been loaded
});

can't run jQuery functions after appending jQuery from same file

I'm appending into my page multiple scripts including jQuery, jQuery migrate... all from same .js file
this is how it looks:
function appendScript(pathToScript, run) {
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
if(run == true){
js.onreadystatechange = function () {
if (this.readyState == 'complete') runFunctions();
}
js.onload = runFunctions;
}
js.src = pathToScript;
head.appendChild(js);
}
appendScript("http://code.jquery.com/jquery-latest.min.js");
appendScript("http://code.jquery.com/jquery-migrate-1.3.0.min.js", true);
function runFunctions(){
console.log('test') // all good till here
// here i have only jquery functions
$('#myDiv').addClass('test');
alert("this doesn't work");
....
}
My problem is that I can't run $(document).ready or any jQuery function, only javascript.
Tried with timeout too. Also I already have 1 x $(window).bind("load", function(){...} so I don't need 1 more
Since jQuery Migrate depends on jQuery, you need to wait until loading the next script.
Here is a working example (I also cleaned up some variables).
function appendScript(src, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
if (callback) {
script.onload = callback;
}
script.src = src;
head.appendChild(script);
}
appendScript("https://code.jquery.com/jquery-latest.min.js", function() {
appendScript("https://code.jquery.com/jquery-migrate-1.3.0.min.js", function() {
document.body.innerHTML = 'Loaded jQuery version ' + jQuery.fn.jquery;
});
});
See working jsfiddle.

Js/jQuery include function not working in IE

i have following Code
function includeJSLib(lib, id, callback) {
if (!document.getElementById(id)) {
var s = document.createElement('script');
s.setAttribute('id', id);
s.setAttribute('async', 'false');
s.setAttribute('type', 'text/javascript');
s.src = lib;
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = callback;
} else {
callback();
}
}
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function(){
jQuery(document).ready( function($) {
if ($('body').hasClass('class')) { do something }
});
});
it will load jQuery. In the callback function there is some custom code. the custom code works fine in Firefox and Chrome but not in IE.
The internet Explorer totally ignores the code snippets. Tested in IE 10/11.
Does anybody have a idea what the problem could be?
Thanks & Regards,
Noxx
p.s. The IE Debugger says nothing, it just jumps over the snippets. And i have to include jQuery this way (better dont ask :P)
For IE instead of onload use onreadystatechange:
function includeJSLib(lib, id, callback) {
if (!document.getElementById(id)) {
var s = document.createElement('script');
s.setAttribute('id', id);
s.setAttribute('async', 'false');
s.setAttribute('type', 'text/javascript');
s.src = lib;
document.getElementsByTagName('head')[0].appendChild(s);
var loaded = false;
s.onload = s.onreadystatechange = function() {
var readyState = this.readyState || 'complete';
if (!loaded && ('loaded' === readyState || 'complete' === readyState)) {
loaded = true;
// Handle memory leak in IE
s.onload = s.onreadystatechange = null;
s.parentNode.removeChild(s);
callback();
}
};
// s.onload = callback;
} else {
callback();
}
}
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function() {
jQuery(document).ready( function($) {
if ($('body').hasClass('class')) { do something }
});
});

Load jQuery dynamically

I am having issues with loading jQuery with Javascript. I need to load it with Javascript because there are conditions that I only can know client-side. The commented out code is supposed to initialize the scripts, but I am having no luck with them.
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")
//script_tag.onload = main; // Run main() once jQuery has loaded
//script_tag.onreadystatechange = function () { // Same thing but for IE
//if (this.readyState == 'complete' || this.readyState == 'loaded') main();
//}
document.getElementsByTagName("head")[0].appendChild(script_tag);
http://mybsabusiness.com/samplesites/silver/sbsa01/
This is the site that the problems are on.
From the jQuerify bookmarlet :
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js',function() {
// Yay jQuery is ready \o/
});​

Categories