I am using Google API, based on their link I have to put the following script in the HTML file
<script src="https://apis.google.com/js/client.js?onload=callback"></script>
The custom callback function is being loaded after the client.js is loaded successfully.
function callback() {
var ROOT = 'https://your_app_id.appspot.com/_ah/api';
gapi.client.load('your_api_name', 'v1', function() {
doSomethingAfterLoading();
}, ROOT);
}
I would like to
Separate HTML with JS file
I downloaded the client.js file and put it in my local repo. But for reducing web request I would like to concat the client.js with other JS file. But I have no idea how to load the content with the concatenated JS file with the callback is being called
Thanks in advance
If you are looking for javascript only solution:
var sScriptSrc = "https://apis.google.com/js/client.js?onload=callback"
loadScript(sScriptSrc);
function loadScript(sScriptSrc) {
var oHead = document.getElementsByTagName("HEAD")[0];
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
oHead.appendChild(oScript);
oScript.onload = loadedCallback();
}
function loadedCallback() {
alert("WoHooo I am loaded");
}
See it running here: JSFiddle
EDIT
Let me do some refining, if I understand correctly what you want to achieve:
I made a simple main html page:
<html>
<head>
<script src="client.js"></script>
</head>
<body>
PAGE BODY
</body>
</html>
Which is loading client.js
client.js contains:
// you can call this function with
// param1: src of the script to load
// param2: function name to be executed once the load is finished
function loadScript(sScriptSrc, loadedCallback) {
var oHead = document.getElementsByTagName("HEAD")[0];
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
oHead.appendChild(oScript);
oScript.onload = loadedCallback;
}
// let's load the Google API js and run function GoggleApiLoaded once it is done.
loadScript("https://apis.google.com/js/client.js", GoggleApiLoaded);
function GoggleApiLoaded() {
alert("WoHooo Google API js loaded");
}
Of course, instead of GoggleApiLoaded example function you could run a method which start the loading of different js and the callback of that one could load a next one and so on...
Is this what you were looking for?
jQuery has a nice method for this. https://api.jquery.com/jquery.getscript/
jQuery.getScript("https://apis.google.com/js/client.js", function() {
console.log("hello");
})
If you want to be compatible with IE, including IE 9, you can use this async JS file loader & callback:
function loadAsync(src, callback){
var script = document.createElement('script');
script.src = src;
script.type = 'text/javascript';
script.async = true;
if(callback != null){
if (script.readyState) { // IE, incl. IE9
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else {
script.onload = function() { // Other browsers
callback();
};
}
}
a=document.getElementsByTagName('script')[0];
a.parentNode.insertBefore(script,a);
}
loadAsync("https://www.example.com/script.js", callbackFunction);
function callbackFunction() {
console.log('Callback function run');
}
Related
I have a cross platform app built using PhoneGap/Cordova.
I am trying to implement a function that runs an external JavaScript file when a controller loads. I am following a solution from HERE. And similarly HERE. But I want the JavaScript to execute without the window.open event, i.e. I want to run executeScript as soon as the device is ready.
How do I call the executeScript() without defining the var ref first though?
var navigation = angular.module("navigation", []);
navigation.controller("Navigation", function ($scope) {
var init = function () {
document.addEventListener("deviceready", onDeviceReady, false);
};
init();
function onDeviceReady() {
// LOAD EXTERNAL SCRIPT
var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
ref.addEventListener("loadstop", function () {
ref.executeScript(
{ file: 'http://haruair.com/externaljavascriptfile.js' },
function () {
ref.executeScript(
{ code: 'getSomething()' },
function (values) {
var data = values[0];
alert("Name: " + data.name + "\nAge: " + data.age);
});
}
);
});
});
You could try to add the script in the index.html file and do whatever you want from JS. Also, you must add to your whitelist this endpoint.
<!-- index.html -->
<script>
function onCustomLoad() {
//do stuff
}
</script>
<script src="your-custom-script" onload="onCustomLoad"></script>
you could use
var script = document.createElement("script");
script.type = "text/javascript";
script.id = "some_id";
script.src = 'http://haruair.com/externaljavascriptfile.js';
document.head.appendChild(script);
then call the function once finished
I have a js file that in which i want to include jquery. in order to include the jquery script i am using this clode:
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
this works, I can see that incuded the script correctly. My inspector shows that it loaded the script but jquery wont work.
any ideas?
You need to make sure the script you are dynamically loading is actually loaded before attempting to use it.
To do so, use script.onload to fire a callback once the load is completed.
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head') [0].appendChild(script);
script.onload = function () {
/* jquery dependent code here */
console.log($);
};
MDN has an example that's more adaptable to a callback you specify -
// from https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement#Dynamically_importing_scripts
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
function importScript (sSrc, fOnload) {
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (fOnload) { oScript.onload = fOnload; }
document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
oScript.src = sSrc;
}
Your jQuery code is not working may be caused by jQuery is not loaded yet while browser executing your jQuery code. Use function below to dynamically load jQuery with callback. Put your jQuery code inside a callback function.
function loadScript(url, callback) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url;
if (typeof(callback) === 'function') {
s.onload = s.onreadystatechange = function(event) {
event = event || window.event;
if (event.type === "load" || (/loaded|complete/.test(s.readyState))) {
s.onload = s.onreadystatechange = null;
callback();
}
};
}
document.body.appendChild(s);
}
/* Load up jQuery */
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function() {
// Put your jQuery code here.
});
You need to include jQuery inside the HTML code. jQuery won't work for you because your script is loaded before jQuery is loaded.
I have a JavaScript file, which also uses jQuery in it too. To load it, I wrote this code:
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
alert("1");
$(document).read(function(){});
alert("2");
This fires alert("1"), but the second alert doesn't work. When I inspect elements, I see an error which says that $ in not defined.
How should I solve this problem?
You need to execute any jQuery specific code only once the script is loaded which obviously might happen at a much later point in time after appending it to the head section:
function include(filename, onload) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
script.onload = script.onreadystatechange = function() {
if (script.readyState) {
if (script.readyState === 'complete' || script.readyState === 'loaded') {
script.onreadystatechange = null;
onload();
}
}
else {
onload();
}
};
head.appendChild(script);
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
$(document).ready(function() {
alert('the DOM is ready');
});
});
And here's a live demo.
You may also take a look at script loaders such as yepnope or RequireJS which make this task easier.
The problem here is probably that, even though you include the script, it doesn't mean it is loaded when you try to do $(document).ready(function(){});. You could look into Google Loader to prevent this problem http://code.google.com/intl/fr-FR/apis/loader/
I have a initializor.js that contains the following:
if(typeof jQuery=='undefined')
{
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
headTag.appendChild(jqTag);
}
I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.
However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:
"jQuery is undefined".
Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!
Also, can I dynamically add code into the $(document).ready() event? Or wouldn't it be necessary just to add some Click events to a few elements?
jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.
e.g.
function myJQueryCode() {
//Do stuff with jQuery
}
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
jqTag.onload = myJQueryCode;
headTag.appendChild(jqTag);
} else {
myJQueryCode();
}
To include jQuery you should use this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>
it uses the Google CDN but provides a fallback an has a protocol relative URL.
Note: Be sure to change the version number to the latest version
if window.jQuery is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate
also: you forgot the quotes, if jQuery is not defined:
typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong
you could also:
window.jQuery === undefined //true
If you're in an async function, you could use await like this:
if(!window.jQuery){
let script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
}
/* Your jQuery code here */
If you're not, you can use (async function(){/*all the code*/})() to wrap and run all the code inside one
.
Alternatively, refactoring Adam Heath's answer (this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.
jQueryCode = function(){
// your jQuery code
}
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
Or you could also wrap it in a function to change the order of the code
function runWithJQuery(jQueryCode){
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
}
runWithJQuery(function jQueryCode(){
// your jQuery code
})
The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.
You can get it from their website.
Example taken from their website:
yepnope([{
load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('local/jquery.min.js');
}
}
}
This site code is solved my problem.
function loadjQuery(url, success){
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
head.appendChild(script);
// 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);
}
};
}
if (typeof jQuery == 'undefined'){
loadjQuery('http://code.jquery.com/jquery-1.10.2.min.js', function() {
// Write your jQuery Code
});
} else {
// jQuery was already loaded
// Write your jQuery Code
}
http://99webtools.com/blog/load-jquery-if-not-already-loaded/
This is old post but I create one workable solution tested on various places.
Here is the code.
<script type="text/javascript">
(function(url, position, callback){
// default values
url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
position = position || 0;
// Check is jQuery exists
if (!window.jQuery) {
// Initialize <head>
var head = document.getElementsByTagName('head')[0];
// Create <script> element
var script = document.createElement("script");
// Append URL
script.src = url;
// Append type
script.type = 'text/javascript';
// Append script to <head>
head.appendChild(script);
// Move script on proper position
head.insertBefore(script,head.childNodes[position]);
script.onload = function(){
if(typeof callback == 'function') {
callback(jQuery);
}
};
} else {
if(typeof callback == 'function') {
callback(jQuery);
}
}
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){
console.log($);
}));
</script>
Explanation you can find HERE.
Problem:
Load js files asynchronously, then check to see if the dom is loaded before the callback from loading the files is executed.
edit: We do not use jQuery; we use Prototype.
edit: added more comments to the code example.
I am trying to load all of my js files asynchronously so as to keep them from blocking the rest of the page. But when the scripts load and the callback is called, I need to know if the DOM has been loaded or not, so I know how to structure the callback. See below:
//load asynchronously
(function(){
var e = document.createElement('script');
e.type = "text/javascript";
e.async = true;
e.src = srcstr;
// a little magic to make the callback happen
if(navigator.userAgent.indexOf("Opera")){
e.text = "initPage();";
}else if(navigator.userAgent.indexOf("MSIE")){
e.onreadystatechange = initPage;
}else{
e.innerHTML = "initPage();";
}
// attach the file to the document
document.getElementsByTagName('head')[0].appendChild(e);
})();
initPageHelper = function(){
//requires DOM be loaded
}
initPage = function(){
if(domLoaded){ // if dom is already loaded, just call the function
initPageHelper();
}else{ //if dom is not loaded, attach the function to be run when it does load
document.observe("dom:loaded", initPageHelper);
}
}
The callback gets called properly due to some magic behind the scenes that you can learn about from this Google talk: http://www.youtube.com/watch?v=52gL93S3usU&feature=related
What's the easiest, cross-browser method for asking if the DOM has loaded already?
EDIT
Here's the full solution I went with.
I included prototype and the asynchronous script loader using the normal method. Life is just so much easier with prototype, so I'm willing to block for that script.
<script type="text/javascript" src="prototype/prototype.js"></script>
<script type="text/javascript" src="asyncLoader.js"></script>
And actually, in my code I minified the two files above and put them together into one file to minimize transfer time and http requests.
Then I define what I want to run when the DOM loads, and then call the function to load the other scripts.
<script type="text/javascript">
initPage = function(){
...
}
</script>
<script type="text/javascript">
loadScriptAsync("scriptaculous/scriptaculous.js", initPage);
loadScriptAsync("scriptaculous/effects.js", initPage);
loadScriptAsync("scriptaculous/controls.js", initPage);
...
loadScriptAsync("mypage.js", initPage);
</script>
Likewise, the requests above are actually compressed into one httpRequest using a minifier. They are left separate here for readability. There is a snippet at the bottom of this post showing what the code looks like with the minifier.
The code for asyncLoader.js is the following:
/**
* Allows you to load js files asynchronously, with a callback that can be
* called immediately after the script loads, OR after the script loads and
* after the DOM is loaded.
*
* Prototype.js must be loaded first.
*
* For best results, create a regular script tag that calls a minified, combined
* file that contains Prototype.js, and this file. Then all subsequent scripts
* should be loaded using this function.
*
*/
var onload_queue = [];
var dom_loaded = false;
function loadScriptAsync(src, callback, run_immediately) {
var script = document.createElement('script');
script.type = "text/javascript";
script.async = true;
script.src = src;
if("undefined" != typeof callback){
script.onload = function() {
if (dom_loaded || run_immediately)
callback();
else
onload_queue.push(callback);
// clean up for IE and Opera
script.onload = null;
script.onreadystatechange = null;
};
script.onreadystatechange = function() {
if (script.readyState == 'complete'){
if (dom_loaded || run_immediately)
callback();
else
onload_queue.push(callback);
// clean up for IE and Opera
script.onload = null;
script.onreadystatechange = null;
}else if(script.readyState == 'loaded'){
eval(script);
if (dom_loaded || run_immediately)
callback();
else
onload_queue.push(callback);
// clean up for IE and Opera
script.onload = null;
script.onreadystatechange = null;
}
};
}
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}
document.observe("dom:loaded", function(){
dom_loaded = true;
var len = onload_queue.length;
for (var i = 0; i < len; i++) {
onload_queue[i]();
}
onload_queue = null;
});
I added the option to run a script immediately, if you have scripts that don't rely on the page DOM being fully loaded.
The minified requests actually look like:
<script type="text/javascript" src="/min/?b=javascript/lib&f=prototype/prototype.js,asyncLoader.js"></script>
<script type="text/javascript"> initPage = function(e){...}</script>
<script type="text/javascript">
srcstr = "/min/?f=<?=implode(',', $js_files)?>";
loadScriptAsync(srcstr, initPage);
</script>
They are using the plugin from: [http://code.google.com/p/minify/][1]
What you need is a simple queue of onload functions. Also please avoid browser sniffing as it is unstable and not future proof. For full source code see the [Demo]
var onload_queue = [];
var dom_loaded = false;
function loadScriptAsync(src, callback) {
var script = document.createElement('script');
script.type = "text/javascript";
script.async = true;
script.src = src;
script.onload = script.onreadystatechange = function() {
if (dom_loaded)
callback();
else
onload_queue.push(callback);
// clean up for IE and Opera
script.onload = null;
script.onreadystatechange = null;
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}
function domLoaded() {
dom_loaded = true;
var len = onload_queue.length;
for (var i = 0; i < len; i++) {
onload_queue[i]();
}
onload_queue = null;
};
// Dean's dom:loaded code goes here
// do stuff
domLoaded();
Test usage
loadScriptAsync(
"http://code.jquery.com/jquery-1.4.4.js",
function() {
alert("script has been loaded");
}
);
You can always put your initial loader script at the bottom, right before the closing body tag.