If you would like to get to the point, here is my question:
Is there any way to call a specific script to load first in javascript?
For more detail, please read below:
I have a javascript file that is loading from the bottom of my HTML <body>. Unfortunately, there is no JQuery in the head, so I have to add it through this javascript file.
What I need to do is add a JQuery lightbox plugin.
My problem is that when I load the page, sometimes JQuery isn't the first thing loaded. So I receive the error "jQuery is not defined". Which will then raise more errors for undefined methods from the plugin.
This doesn't happen all the time, only sometimes. Which makes me think it's a loading/order of operations issue.
Is there any way I can guarantee that my JQuery script is the first thing loaded?
Here is some of my javascript file.
//Get head element
var head = document.getElementsByTagName("head")[0];
//Create and insert JQuery
var jquery = document.createElement('script');
jquery.type = 'text/javascript';
jquery.src = 'http://image.iloqal.com/lib/fe6b/m/1/jquery.1.7.2.js';
head.insertBefore(jquery,head.childNodes[4]);
function thescripts() {
var fancybox = document.createElement('script');
fancybox.type = 'text/javascript';
fancybox.src = 'http://image.iloqal.com/ilejquery.fancybox-1.3.4.pack.js';
head.appendChild(fancybox);
var thebody = document.getElementsByTagName('body')[0];
thebody.appendChild(thediv);
thediv.appendChild(theimg);
//Run fancybox
thebody.onload = function() {
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
};
if(jquery.attachEvent){
jquery.attachEvent("onload",thescripts());
} else {
jquery.onload = thescripts();
}
Any help is appreciated!
Try this. Add this piece of code inside your javascript file which is called from your footer.
<script type="text/javascript">
if(typeof jQuery == 'undefined'){
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}
</script>
This will include jquery if its not loaded. I think this will fix your issue.
Using $(function() {...do your stuff here...}); is the way to go to be sure jQuery is loaded before the script is executed, but you could probably make it harder for yourself and do:
thebody.onload = function() {
RunMyjQuery();
}
function RunMyjQuery() {
if (typeof $ === 'undefined') {
setTimeout(RunMyjQuery, 500);
}else{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
}
You're calling thescripts immediately, although you try not to. Use this:
jquery.onload = thescripts; // notice no parentheses
Also, your thebody.onload strategy will not work. Use $(document).ready instead:
$(document).ready(function{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
});
Related
i'm having issues with injecting jQuery into an iframe. With regular javascript it works as intended, but not with jQuery.
I have appended the jQuery CDN link to the iframes <head> and if I inspect the iframe element i can see it there. I can also see the scripts in the body tag after the function has run.
When executing the jquery script i get this error.
Uncaught ReferenceError: $ is not defined
If i add these I don't get the error but nothing happens.
$iframe[0].contentWindow.$ = $;
$iframe[0].contentWindow.jQuery = $;
I've tried to add timeouts to the append function to see if it was an issue with the CDN not loading quick enough. But no difference.
If i put the HTML and jQuery outside the iframe everything works as intended so I think there is something i've done wrong or missed regarding the iframe. Anyone have an idea what I could've done wrong here?
This is the function that injects the scripts
injectScript() {
let $iframe = $('#iframe');
$iframe.ready(function () {
$iframe[0].contentWindow.$ = $;
$iframe[0].contentWindow.jQuery = $;
const jqueryScript = document.createElement("script");
jqueryScript.type = "text/javascript";
jqueryScript.src = "https://code.jquery.com/jquery-3.5.1.min.js"
$iframe.contents().find("head").append(jqueryScript);
// This code works
let vanilla = "<script>document.getElementById('vanilla').innerHTML = 'bar'<";
vanilla += "/script>";
$iframe.contents().find("body").append(vanilla);
// This code works **not**
let jQuery = "<script>$('#jquery').text('foo')<";
jQuery += "/script>";
$iframe.contents().find("body").append(jQuery);
})
}
the html in the iframe
<div id="jquery">foo</div>
<div id="vanilla">foo</div>
I have the script audiojs for changing the style of audios tag in html when I go to my page it work without problems, but when I click a button to reload div (this div contain audios tags) with function load jQuery the style of audiojs removed, I tried to get script after load the div with jQuery getScript, but the script load many times that caused to stop of my browser.
this is the function to call the audiojs
audiojs.events.ready(function() {
audiojs.createAll();
});
I want a solution to call this function one time no more, thanks
Try to adding a new script tag to with the script to re-load in your code something like below:
<script language="text/javascript">
function audiojs()
{
var div= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'audiojs.js';
div.appendChild(script);
}
audiojs();
</script>
I hope you will get some ideas now. Also check your caching.
It's hard to know without any link to the audio.js library, but most API's or libraries will give some indication that they are loaded. I would use an if statement to create something like:
(function () {
function checkForLoaded(){
if (audiojs.state !== null) { //or something similar
audiojs.createAll();
}
}
})();
Thanks everyone,
i found the solution,
after loading the div with ajax i added this code to remove the class audiojs
$("audio").removeClass("audiojs");
I have a little issue bugging me for several hours now, so i come to see you guys for some help.
Here is the situation :
I use jquery-2.1.4.js in my application. If i test my fragment of code outside the application it work correctly but when it is in my application Jquery doesn't load correctly.
Jquery is include correctly in my repository and called in my page before the end of the body tag like this (i moved it away from the head tag thiking it might be the issue but i still got the same error) :
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
I test if Jquery is correctly loaded like this :
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
alert("jquery not loaded,force it");
var jq = document.createElement('script');
jq.type = 'text/javascript';
// Path to jquery.js file, eg. Google hosted version
jq.src = 'js/jquery-2.1.4.js';
document.getElementsByTagName('head')[0].appendChild(jq);
} else {
// jQuery is loaded
alert("jquery is loaded");
}
The issue is here now :), everytime I end up in the not loaded part, and when I force Jquery load, I got an error line 3539 of the Jquery file on the function :
function Data() {
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Data.uid++;
}
With the error message :
This object does not have this property or method : defineProperty
(not sure about the English for this one, my error message is in French).
Just so you know, there is no action done on Load, only when i click a button. Our file with JS codes are in a .include, so i don't know if this is why the error is trigger or not.
Anyway, thanks for taking the time to help me.
Slayner.
You need to include the expando library, since it is not part of standard jQuery. Try adding this:
<script src="//cdn.rawgit.com/cantino/expando/38affee59bffdd87975c492472362c69ce0f6fda/jquery.expando.js"></script>
Right after this:
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
Okay, so the reason why this did not work for me was that our application is loaded as an IE5 application and is not compatible with JQuery (well not a version from these last few year.)
I need to include jQuery library in javascript file (john.js) remotely. I have tried this without any luck;
(function(d, t) {
var g = d.createElement(t), // create a script tag
s = d.getElementsByTagName(t)[0]; // find the first script tag in the document
g.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
s.parentNode.insertBefore(g, s); // append the script to the DOM
}(document, 'script'));
$( document ).ready(function() {
// My jquery works here
});
I want to fetch a script in javascript way. What is the correct way to do that ?
The error here is that JQuery is not loaded yet when this code is executed:
$(document).ready(function() { .. }
As is, you get an error like this: $ is undefined (or similar)
You should use the onload event of created script element to be sure it is loaded Jquery.
This sample shown how you can achieve your goal. Good Luck.
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
newScript.onload = function() {
alert("Script is ready!");
$(document).ready(function() {
alert("JQuery is ready!");
});
};
var head = document.getElementsByTagName("head")[0];
head.appendChild(newScript);
Here is the answer on how to fetch, coming from an other post :
Adding <script> element to the DOM and have the javascript run?
That beeing said another issue you may have is that when you call your
$( document ).ready(function() {
// My jquery works here
});
Jquery may not be loaded yet
so you can try a recursive function to check if jquery has been loaded with something like that (not teste)...
function launch(callBack){
if (window.jQuery) {
callBack();
} else {
setTimeout(function(){launch(callBack);},100);
}
}
launch(function(){
$( document ).ready(function() {
// My jquery works here
});
});
You can use a combination of an XMLHttpRequest and eval to fetch the javascript file dynamically like getScript does for jQuery.
See my fiddle.
Typically the jquery is called in the html file before custom javascript files are called:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="app.js"></script>
I have script (myscript.js) which create div and animate div in any HTML page. my script is using Jquery animation function
I am currently using following code (it's sample snippet)
<script src="jquery.js"><script>
<script src="myscript.js"><script>
But is this possible to use only following code which can automatically add JQuery library also?
<script src="myscript.js"><script>
Insert this on top of your myscript.js
var h=document.getElementsByTagName('head')[0];
var s=document.createElement('script');
s.type='text/javascript';
s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
h.appendChild(s);
but you will have to wait until script loaded using waitforload function
function w4l(){
if (typeof jQuery != "function"){
setTimeout("w4l()", 1000);
return;
}else{
//Do Jquery thing
}
}
w4l();
or just simply copy all jquery.js code file into your myscript.js, AKA merge 2 file into one
To make sure that the rest of myscript.js doesn't get executed before jQuery is loaded, use something like this:
function dostuff() {
//animate elements, etc.
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'jquery.js';
script.onreadystatechange = dostuff;
script.onload = dostuff;
head.appendChild(script);
Note: it's a bit unclear why you wouldn't want to explicitly add the jQuery part in your head.