How to include jQuery library in Javascript without <script src=""> - javascript

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>

Related

Inserting a <script> tag dynamically via jQuery

I'm trying to add a widget to the page in run-time. Based on this post, I wrote the code below. Unfortunately, it doesn't show anything. Can anybody tell me why?
<script type="text/javascript">
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// Use any selector
$(".testWidget").append(s);
});
</script>
<div class="testWidget">
</div>
If I put the same script as below, it works and shows some information on the page. However, I should insert the script dynamically, not as static.
<div class="testWidget">
<script src="https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7" type="text/javascript" charset="utf-8"></script>
</div>
You should be getting this warning in the console, Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. Here's a way around that:
<script type="text/javascript">
$(document).ready(function () {
// Save a copy of the document.write method
var oldWrite = document.write;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// After script is loaded, revert document.write to the original
s.onload = function () {
document.write = oldWrite;
};
var $testWidget = $('.testWidget');
// Redefine document.write to make the script's call work
document.write = function (html) {
$testWidget.html(html);
};
$testWidget.append(s);
});
</script>
The script tag you include programatically has to be parsed by the browser. Just by inserting the script tag the included code is not parsed by the JavaScript interpreter.
If you explain what you want to finally achieve I am pretty sure that must be a simpler way to do it.

Add jquery script via script file

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.

Loading JQuery with Javascript from footer

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');
});
});

Dynamically loading Java Script files

I would like to know if there is a way to dynamically load some JS files before "$(document).ready" gets called. These JS files should be loaded and available in the ready event handler.
Does jquery provide a way to do this?
The issue here (as you might expect) is the ability to load a specific localized version of my JS files depending on whichever locale/language is selected.
Thanks
If you want in pure javascript you can try this.
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'complete'){
//Your can write your code here
};
}
script.src= 'script.js';
head.appendChild(script);
Alertnatively you can use jQuery's getScript method
$.getScript("script.js", function(){
//Your can write your code here
});
Try this:
jQuery.getScript("url here")
http://api.jquery.com/jQuery.getScript/

Load scripts after page has loaded?

Is it possible to load certain scripts like
<script type="text/javascript" src="somescript.js"></script>
when the rest of the page has loaded?
Imagine I have a few larger script files like this that are not needed when the page is loaded. E.g. I'm using the Google Maps API that is only used when a button is clicked (so not on page load).
Is it possible to load the rest of the page first, before processing all those script tags in my head?
In JQuery you could do this on document ready
$.getScript("somescript.js", function(){
alert("Script loaded and executed.");
});
simply you can add into that script file defer parameter
<script src="pathToJs" defer></script>
you can check this question as well
It is possible. I was doing a similar thing in an AJAX intensive site, but I was loading the Google Charts API. Here is the code I used to load the Google Charts API when a button was clicked on the page.
function loadGoogleChartsAPI() {
var script = document.createElement("script");
// This script has a callback function that will run when the script has
// finished loading.
script.src = "http://www.google.com/jsapi?callback=loadGraphs";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
function loadGraphs() {
// Add callback function here.
}
This uses a callback function that will run when the script has loaded.
No one mentioned these?
$(window).load(function(){
// do something
});
or
$(window).bind("load", function() {
// do something
});
$(document).ready(function() {
var ss = document.createElement("script");
ss.src = "somescript.js";
ss.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(ss);
});
Please see my code. The onload event will occur when the script has finished loading. Or the onerror event will occur.
function loadJavaScript() {
var script = document.createElement("script");
script.src = "javaScript.js";
script.type = "text/javascript";
script.onload = function () {
console.log('script was loaded successfully');
}
script.onerror = function (e) {
console.error('script.onerror');
}
document.getElementsByTagName("head")[0].appendChild(script);
}
Thanks to answer.
Also see my code of the load of the script.
use the getScript method of jquery! or try simply to put this script on the end of the page?
Yes, this is possible by dynamically injecting the JavaScript files from code. There are lots of libraries which you can use:RequireJS, HeadJS etc. Recently I found this document which compares lots of JavaScript loader libraries.
To just allow the page to show before your script is loaded, use the async attribute:
<script src="//url/to/script.js" async></script>
To hide the loading spinner in the browser, append the script tag after the page finished loading:
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = '//url/to/script.js';
document.getElementsByTagName('body')[0].appendChild(script);
});
</script>
Yep, that's completely possible. Add an onLoad="foo();" event to your <body> tag and have it invoke your scripts. You'll need to wrap your external JS in a function and do something like:
//EXTERNAL JS (jsstuff.js)
function Mojo() {
document.getElementById('snacks').style.visibility = "visible";
alert("we are victorious!");
}
//YOUR HTML
<html>
<head>
<script type='text/javascript'></script>
</head>
<body onLoad='Mojo();'>
<div id='snacks'>
<img src='bigdarnimage.png'>
</div>
</body>
</html>

Categories

Resources