jQuery's .getScript()... what am I doing wrong? - javascript

I'm programming an iPhone app with Phonegap. I have local .html and .js files. The following is in my index.html file:
function onBodyLoad() {
document.addEventListener("deviceready", deviceReady, false);
}
function deviceReady() {
$.getScript("js/order.js");
}
I researched and researched, but just can't figure out why my "order.js" file isn't getting called by the $.getScript method. Any ideas? Or is there any other way to call this .js file within the deviceReady function in my index.html?

For me the following solution worked very well.
Add a custom jQuery function that uses ajax and caches the loaded script:
function init()
{
// Create a custom cached script importer based on ajax
jQuery.cachedScript = function(url, options)
{
// Allow custom options, but dataType, cache and url are always predefined
options = $.extend(options || {},
{
dataType: "script",
cache: true,
url: url
});
return jQuery.ajax(options);
};
importScripts();
}
Import the scripts and optionally handle done and fail:
function importScripts()
{
$.cachedScript("js/events.js")
// Wait for the script to be loaded, before adding the listener
.done(function()
{
document.addEventListener("deviceready", onDeviceReady, false);
});
$.cachedScript("js/navigation.js");
$.cachedScript("js/mark.js");
}
Thats it : )
More information may be found here.

Related

HTML load order and dynamically added JS Files

I add some JS files dynamically to my HTML Header and I want to guarantee that my JS files finish loading before I continue to render my Body.
Events like load or DOMContentLoaded trigger after the loading is finished.
my body needs the added scripts to render properly but starts before the files are loaded fully.
Code Snippet:
...
<script>
$.ajax({
type: "Get",
url: '#Url.Action("GetLocalisationFiles", "Localisation")',
success: function (response) {
for (var file in response) {
var scriptName = response[file];
//Adding of the script(s)
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
document.head.appendChild(myScript);
//
}
}
});
window.addEventListener("load", LocalizationAdded);
function LocalizationAdded(e) {
alert("JS Files Finished Loading");
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
}
</script>
</head>
<body class="dx-viewport">
<script>
alert("Body Started");
...
Is there any other event prior to the rendering of the body or an easy way to delay my body rendering?
I know I could manually add all Content that depends on the added scripts after the loading is finished but this seems fuzzy.
The dynamical adding of JS works as intended. My Problem is within the order it happens.
Thanks in advance for any help
Previous question:
How do I reference code in dynamically added js files?
We could question whether loading scripts following some user action, is such a good idea. You could instead load the relevant HTML content from the server (which could include script tags), if you really want to have a one-page experience, or else initiate a navigation, where again the server would get clues via HTTP request on what to generate next.
But, if we stick with this pattern, I would suggest using the onload property of script elements, and to use promises for awaiting all scripts to have been loaded.
Here is some code you could use. This demo loads two JS files after an AJAX call has come back with a response: one for the immutablejs library, the second for the momentjs library.
A new Promise will resolve when the script's load event fires, and Promise.all will resolve when this has happened for all scripts.
For the purpose of demo I replaced the URL with a mock, and also tampered with the response in order to produce a response as you have it:
// dummy server, just for demo
let url = "https://jsonplaceholder.typicode.com/todos/1";
console.log("Launching initial HTTP request...");
$.get(url).then(function (response) {
console.log("Received response. Loading scripts...");
// Overwriting the response with mock data:
response = {
immutable: "https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js",
moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"
};
return Promise.all(Object.values(response).map(function (scriptName) {
return new Promise(function (resolve, reject) {
//Adding of the script(s)
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
myScript.onload = resolve;
myScript.onerror = reject;
document.head.appendChild(myScript);
//
});
}));
}).then(function () {
// All code that depends on the loaded scripts should be here, or called from here
console.log("All scripts loaded:");
console.log("Immutable: ", typeof Immutable);
console.log("moment: ", typeof moment);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remark: the async: false option is deprecated. It is not good practice either. Instead use the Promise that jQuery returns for $.ajax, $.get, ...etc, and chain a then call where you continue processing the result (instead of a success handler). And on once you arrive in the world of promises, you'll find that using async and await syntax can simplify code.

callback function for location.href

We have below code
Javascript:
function Download() {
//Show Loading Spinner
location.href = "FileDownloadHandler.ashx";
//Some Code(Hiding Loading Spinner)
}
aspx page:
<input type="button" value="Download" onclick="Download();" />
"FileDownloadHandler" will download the file to the user.
Actual Result:
Code below location.href is executing immediately without completion of handler execution.
Expected Result:
I want to stop executing "SomeCode" until handler completes the execution.
How can I achieve this?
Thanks in advance.
Finally I found a solution to my problem. Using jQuery plugin we can achieve this. I have implemented it and working like a charm.
This Plugin does file download and it has successs & failure callbacks, so we can have control on the code which should execute after completion of file download.
Here instead of location.href, we have to call this plugin to invoke our FileDownloadHandler as below.
$("#loading").show();
$.fileDownload('FileDownloadHandler.ashx', {
successCallback: function (url) {
$("#loading").hide();
},
failCallback: function (html, url) {
$("#loading").hide();
alert("Failed");
}
});
More details below
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
http://jqueryfiledownload.apphb.com/
http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js
Consider using the Jquery get function: https://api.jquery.com/jquery.get/
$.get("FileDownloadHandler.ashx", function() {
alert("Called Ashx Page");
})
.done(function() {
alert("Stuff to do after ashx");
})

Issue calling a js function on load in index.html

I wan to call a js function when the index.html loads.
This js function is defined in main.js file.
I am able to call it using the below way
<input type="button" value="Submit" onclick="getSecretData()" />
But i want this function to be called every time the index.html is loaded (instead of the button)
I tried the below code. Its not working. Can you please help ?
index.html
<script>
$(document).ready(function() {
getSecretData();
});
</script>
main.js
function getSecretData(){
var invocationData = {
adapter: "DummyAdapter",
procedure: "getSecretData",
parameters: []
};
WL.Client.invokeProcedure(invocationData, {
onSuccess: getSecretData_Callback,
onFailure: getSecretData_Callback
});
}
function getSecretData_Callback(response){
alert("getSecretData_Callback response :: " + JSON.stringify(response));
}
Thanks
You are using Worklight. Did you read the training materials?
Other answers given here could work for you, but because you are using Worklight, you should do it in the more appropriate approach for Worklight-based applications.
In your Worklight application, in common\js\main.js, there is wlCommonInit().
If you want some code to run when you start your app, place it there.
function wlCommonInit() {
myFunction();
}
function myFunction(){
// whatever you want to run...
}
Note though, that it is not smart to invoke adapters on application startup. Adapters require connection to the Worklight Server, so what you want to do is to first try and connect to the server using WL.Client.connect and if you succeed in doing so, only then invoke the adapter via the connect's onSuccess callback.
WL.Client.connect({onSuccess: myFunction, onFailure: connectionFailure});
For example:
function wlCommonInit() {
WL.Client.connect({
onSuccess: myFunction,
onFailure: connectionFailure
});
}
function myFunction(){
// whatever you want to run...
}
function connectionFailure(){
// ...
}
You can try this.
document.querySelector('body').addEventListener("load", getSecretData, false);
For more information I recommend reading this previous answer or MDN's page

onload event listener called many times when loading just one page in Firefox extension

I wrote a program to capture browser side implicit indicators using Javascript and PHP. The program is working very well as a standalone on a single index page. I tried adding it as an extension in Firefox so that users can access it remotely and to capture all URL visited. As I added it, I discovered that it fires whenever a single file (such as html, jpg, css, js) has loaded thereby given me multiple loads. Please How can I make the associated files fire at the same time like a single file? Below is the code section:
var linkTargetFinder = function () {
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
return {
selectedTab: null,
init: function () {
gBrowser.addEventListener("load", function (e) {
linkTargetFinder.run(e);
}, false);
},
run: function (e) {
var doc = e.originalTarget;
doc.defaultView.addEventListener("unload", function (e) {
alert('Unloading tab');
linkTargetFinder.setCloseEvent();
}, false);
},
}
}();
window.addEventListener("load", linkTargetFinder.init, false);

how to load google client.js dynamically

this is my first time to post here on stackoverflow.
My problem is simple (I think). I am tasked to allow users to sign up using either Facebook, Google Plus, LinkedIn and Twitter. Now, what I want to do is when the user clicks the Social Network button, it will redirect them to the registration page with a flag that determines which social network they want to use. No problem here.
I want to load each API dynamically depending on which social network they choose.
I have a problem when loading the Google JS API, dynamically. The sample found in here loads client.js in a straightforward manner. I have no problems if I follow the sample code. But I want to load it dynamically.
I tried using $.ajax, $.getScript and even tried adding the script to the page just like how you call Google Analytics asynchronously. None of the above worked. My call back function is NOT called all the time. Also, if i call the setApiKey from the call back function of $.ajax and $.getScript, the gapi.client is NULL. I don't know what to do next.
Codes that did not work:
(function () {
var gpjs = document.createElement('script'); gpjs.type = 'text/javascript'; gpjs.async = false;
gpjs.src = 'https://apis.google.com/js/client.js?onload=onClientLoadHandler';
var sgp = document.getElementsByTagName('script')[0]; sgp.parentNode.insertBefore(gpjs, sgp);})();
Using $.getScript
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
Using $.ajax
$(document).ready(function () {
$.ajax({
url: "https://apis.google.com/js/client.js?onload=onClientLoad",
dataType: "script",
success: function () {
console.log("GP load successful");
SetKeyCheckAuthority();
},
error: function () { console.log("GP load failed"); },
complete: function () { console.log("GP load complete"); }
});});
May I know what is the proper way of calling this js file dynamically? Any help would be appreciated. Thank you.
Ok, I just thought of a solution but i think it's a bad one. Please let me know what you think of it.
i used $.getScript to load the js file
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
and then on my SetKeyCheckAuthority function i placed a condition to call itself after 1 second when gapi.client is null.
function SetKeyCheckAuthority() {
if(null == gapi.client) {
window.setTimeout(SetKeyCheckAuthority,1000);
return;
}
//set API key and check for authorization here }

Categories

Resources