The function should be callable - javascript

I have two js files. In the first I use this code:
var rightsRef = db.collection("users").doc(uid).collection("rights");
if(createDocumentWithoutId(rightsRef, "readGrades", "false", null, null, null, null) === true) {
window.location.href = "../public/main/main_index.html";
}
else {
}
In the second js file, I use this code:
function createDocumentWithoutId(var databaseRef, var titleValue1, var contentValue1, var titleValue2, var contentValue2, var titleValue3, var contentValue3) {
databaseRef.set({
titleValue1: contentValue1,
titleValue2: contentValue2,
titleValue3: contentValue3,
}).then(function() {
return true;
}).catch(function(error) {
console.error("Error adding document: ", error);
return false;
});
}
That I can call the function of the second js file I "import" both of them in the HTML file, by this way:
<script type="text/javascript" src="javascript1.js"></script>
<script type="text/javascript" src="../javascript2_folder/javascript2.js"></script>
But I am getting this Error:
ReferenceError: createDocumentWithoutId is not defined

You first JS file is being fully executed before the second one. That's what's causing your error - the function in the second file hasn't been loaded yet. You could reverse the order that they're define in your HTML so that the function is defined before it's called.

JS files execute when they're loaded, and in this case execution includes defining the functions. Try reversing the load order of your files, or putting some sort of check on the first code, such as this:
function amIDependentOnAnotherFile(){
if (typeof functionInAnotherFile == 'undefined')
return setTimeout(amIDependentOnAnotherFile, 5);
doSomething();
}

Related

load inserted script, making sure that libraries load first [duplicate]

I'm creating a jquery plugin and I want to verify an external script is loaded. This is for an internal web app and I can keep the script name/location consistent(mysscript.js). This is also an ajaxy plugin that can be called on many times on the page.
If I can verify the script is not loaded I'll load it using:
jQuery.getScript()
How can I verify the script is loaded because I don't want the same script loaded on the page more than once? Is this something that I shouldn't need to worry about due to caching of the script?
Update:
I may not have control over who uses this plugin in our organization and may not be able to enforce that the script is not already on the page with or without a specific ID, but the script name will always be in the same place with the same name. I'm hoping I can use the name of the script to verify it's actually loaded.
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
Update
You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter() functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
Few too many answers on this one, but I feel it's worth adding this solution. It combines a few different answers.
Key points for me were
add an #id tag, so it's easy to find, and not duplicate
Use .onload() to wait until the script has finished loading before using it
mounted() {
// First check if the script already exists on the dom
// by searching for an id
let id = 'googleMaps'
if(document.getElementById(id) === null) {
let script = document.createElement('script')
script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + apiKey)
script.setAttribute('id', id)
document.body.appendChild(script)
// now wait for it to load...
script.onload = () => {
// script has loaded, you can now use it safely
alert('thank me later')
// ... do something with the newly loaded script
}
}
}
#jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:
function isScriptLoaded(src)
{
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
UPDATE July 2021:
The accepted solutions above have changed & improved much over time. The scope of my previous answer above was only to detect if the script was inserted in the document to load (and not whether the script has actually finished loading).
To detect if the script has already loaded, I use the following method (in general):
Create a common library function to dynamically load all scripts.
Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).
I use something like the following loadScript() function to load the script that uses callback functions to inform the calling modules if the script finished loading successfully.
I also use additional logic to retry when script loading fails (in case of temporary network issues).
Retry is done by removing the <script> tag from the body and adding it again.
If it still fails to load after configured number of retries, the <script> tag is removed from the body.
I have removed that logic from the following code for simplicity. It should be easy to add.
/**
* Mark/store the script as fully loaded in a global variable.
* #param src URL of the script
*/
function markScriptFullyLoaded(src) {
window.scriptLoadMap[src] = true;
}
/**
* Returns true if the script has been added to the page
* #param src URL of the script
*/
function isScriptAdded(src) {
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
/**
* Returns true if the script has been fully loaded
* #param src URL of the script
*/
function isScriptFullyLoaded(src) {
return src in window.scriptLoadMap && window.scriptLoadMap[src];
}
/**
* Load a script.
* #param src URL of the script
* #param onLoadCallback Callback function when the script is fully loaded
* #param onLoadErrorCallback Callback function when the script fails to load
* #param retryCount How many times retry laoding the script? (Not implimented here. Logic goes into js.onerror function)
*/
function loadScript(src, onLoadCallback, onLoadErrorCallback, retryCount) {
if (!src) return;
// Check if the script is already loaded
if ( isScriptAdded(src) )
{
// If script already loaded successfully, trigger the callback function
if (isScriptFullyLoaded(src)) onLoadCallback();
console.warn("Script already loaded. Skipping: ", src);
return;
}
// Loading the script...
const js = document.createElement('script');
js.setAttribute("async", "");
js.src = src;
js.onload = () => {
markScriptFullyLoaded(src)
// Optional callback on script load
if (onLoadCallback) onLoadCallback();
};
js.onerror = () => {
// Remove the script node (to be able to try again later)
const js2 = document.querySelector('script[src="' + src +'"]');
js2.parentNode.removeChild(js2);
// Optional callback on script load failure
if (onLoadErrorCallback) onLoadErrorCallback();
};
document.head.appendChild(js);
}
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion #Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
Create the script tag with a specific ID and then check if that ID exists?
Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?
Edit: following feedback that a code example would be useful:
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
if(scripts.length){
for(var scriptIndex in scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
for(var scriptIndex in document.scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:
function check_script_loaded(glob_var) {
if(typeof(glob_var) !== 'undefined') {
// do your thing
} else {
setTimeout(function() {
check_script_loaded(glob_var)
}, 100)
}
}
Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :
if(!$("body").data("google-map"))
{
console.log("no js");
$.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
$("body").data("google-map",true);
},function(){
alert("error while loading script");
});
}
}
else
{
console.log("js already loaded");
}
I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again.
It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.
window.addEventListener('error', function(e) {
if (e.target.nodeName === 'SCRIPT') {
var scriptTag = document.createElement('script');
scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
document.head.appendChild(scriptTag);
}
}, true);
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
My idead is to listen the error log if there is an error on script loading.
const checkSegmentBlocked = (e) => {
if (e.target.nodeName === 'SCRIPT' && e.target.src.includes('analytics.min.js')) {
window.isSegmentBlocked = true;
e.target.removeEventListener(e.type, checkSegmentBlocked);
}
};
window.addEventListener('error', checkSegmentBlocked, true);
Some answers on this page are wrong. They check for the existence of the <script> tag - but that is not enough. That tells you that the tag was inserted into the DOM, not that the script is finished loading.
I assume from the question that there are two parts: the code that inserts the script, and the code that checks whether the script has loaded.
The code that dynamically inserts the script:
let tag = document.createElement('script');
tag.type = 'text/javascript';
tag.id = 'foo';
tag.src = 'https://cdn.example.com/foo.min.js';
tag.onload = () => tag.setAttribute('data-loaded', true); // magic sauce
document.body.appendChild(tag);
Some other code, that checks whether the script has loaded:
let script = document.getElementById('foo');
let isLoaded = script && script.getAttribute('data-loaded') === 'true';
console.log(isLoaded); // true
If the both of those things (inserting and checking) are in the same code block, then you could simplify the above:
tag.onload = () => console.log('loaded');
I found a quick tip before you start diving into code that might save a bit of time. Check devtools on the webpage and click on the network tab. The js scripts are shown if they are loaded as a 200 response from the server.

ReferenceError: functionxyz is not defined

I am having an error that kinda makes me upset atm. I have three script files, one jQuery, another one including all my functions and the last one is a file where I use one of the function in the functions-script-file.
<!-- SCRIPTS -->
<script type="text/javascript" src="http://localhost/assets/web/js/jquery/de.jq.311.js"></script>
<script type="text/javascript" src="http://localhost/assets/web/js/func.js"></script>
<script type="text/javascript" src="http://localhost/assets/web/js/sign/signup.js"></script>
Signup.js now tells me that a certain function that actually is defined in func.js is not defined, even tho they are all in the correct order and I have checked it twice, the function is spelled the right way. I also have tried to put the functions directly in the head tag above the signup.js and that worked just fine.
func.js:
$(document).ready(function(){
// VARS
var body = $('body');
// FUNCTIONS
var dialerTimeout;
function showDialer(text) {
var t = text;
clearTimeout(dialerTimeout);
var rd = $('response-dialer');
rd.find('.inr p').html(text);
rd.css('bottom', '12px');
dialerTimeout = setTimeout(function(){ rd.removeAttr('style'); }, 3000);
}
});
signup.js:
$(document).ready(function(){
$(document).on('click', '[data-action="signup"]', function(){
var mail = $('input[name="mail"]').val();
var pass = $('input[name="password"]').val();
var pass2 = $('input[name="password2"]').val();
var agb = $('input[name="agb"]').val();
var rd = $('response-dialer');
var lc = $('login-container');
console.log($('[data-form="signup"]').serialize());
if(mail === '' || pass === '' || pass2 === '') {
showDialer('Bitte fülle alle Felder aus!');
} else if(pass !== pass2) {
showDialer('Ihre Passwörter stimmen nicht überein!');
} else if(grecaptcha && grecaptcha.getResponse().length === 0) {
showDialer('Der Captcha-Code ist falsch!');
} else if(!($('#agb').is(":checked"))) {
showDialer('Bitte lese und akzeptiere unsere AGB!');
} else {
if(!validateEmail(mail)) {
showDialer('Ihre E-Mail hat ein falsches Format. Bitte nutze name#host.endung');
} else {
addOverlay(lc);
}
}
});
});
You are getting the error because showDialer is only in the scope of the callback passed to $(document).ready in funcs.js. In order to use it in another script, you have to either define it as a global function, or (better) combine your 2 scripts into one file with just the one $(document).ready enclosing everything.
The issue is your scope. You're defining the functionxyz within the $(document).ready() scope within the first file, which means it's unavailable to the second file, even though their "scope" is the same (document.ready).
You need to define the function you want outside of the document.ready scope so that it can be globally accessed by the signup.js file.
That's because you are wrapping each one of them in a separated $(document).ready function which explains that behavior.
If you don't really need the $(document).ready function for a specific purpose, I would recommend to remove it from both of them and your code will work just fine. But, in case you need it for any reason, just wrap both files together under ONE $(document).ready function so that you can access it without any scoping issue!
For more information about Scope in Javascript, feel free to check this Scope Guide from Scotch.io

Use global variables declared in a javascript file in another javascript file

I'm trying to get TestService.Server.WWW_SERVER_URL, but TestService.Server is undefined.
When I call test1(), it works well. But I cannot access the object literal TestServer.
Is there a different way?
test.html
<script type="text/javascript" language="javascript" src="TestService.js"></script>
<script type="text/javascript" language="javascript">
function test() {
alert("TestService.Server.WWW_SERVER_URL[" + TestService.Server.WWW_SERVER_URL + "]");
//test1();
}
</script>
TestService.js
document.write("<scr" + "ipt type='text/javascript' src='TestServer.js'><" + "/scr" + "ipt>");
var TestService = {
Server: TestServer,
Delimiter: ""
};
function test1() {
test2();
}
TestServer.js
var TestServer = {
WWW_SERVER_URL: "http://www.test.com"
};
function test2() {
alert("test2 has been called!");
}
You have this in your TestService.js
document.write("<scr" + "ipt type='text/javascript' src='TestServer.js'><" + "/scr" + "ipt>");
var TestService = {
Server: TestServer,
Delimiter: ""
};
you are trying to set a property in TestService with TestServer which hasnt loaded yet as you do not give time for the newly added script to load
TestService.Server will evaluate to undefined since TestServer does not exist yet
Setup an onload function that will add your script and then set your TestService.Server variable when its loaded
var TestService = {
Server: null,
Delimiter: ""
};
function test1() {
test2();
}
window.onload = function() {
var head = document.querySelector("head");
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "TestServer.js");
head.addEventListener("load", function(event) {
if (event.target.nodeName === "SCRIPT"){
TestService.Server = TestServer;
}
}, true);
head.appendChild(script);
}
If you attach scripts dynamically, IE, Firefox, and Chrome will all
download the scripts in an asynchronous manner.
Firefox and Chrome will wait till all of the async requests return and
then will execute the scripts in the order that they are attached in
the DOM but IE executes the scripts in the order that they are
returned over the wire.
source
In your case, you can't gurantee TestServer.js get executed before TestService.js. So I will recommend you change the way you access global variable cross-file.
You can add TestServer.js to your html right before TestService.js, so they can execute one by one.
Anyhow, it is NOT recommended to do stuff like this, you can wrap them in your own namespace. Plus you'd better check the variable you want to use cross-file whether it's undefined before you use it.

Loading javascript files in js files. Which is best way to check whether all files are loaded or not?

I have a array where i have specified the files i need to load in javascript before calling specific script. Lets call those particular lines of code as myscript.
I did as follows
var fileNamesArray = new Array();
fileNamesArray.push("abc.js");
fileNamesArray.push("pqr.js");
fileNamesArray.push("xyz.js");
fileNamesArray.push("klm.js");
var totalFiles = jQuery(fileNamesArray).length;
var tempCount = 0;
jQuery.each(fileNamesArray, function(key, value) {
jQuery.getScript(value, function() {
tempCount++;
});
});
to check whether all files are being loaded or not, i done following thing but doesn't seems to be effective
var refreshIntervalId = setInterval(function() {
if (tempCount == totalFiles) {
clearInterval(refreshIntervalId);
return;
}
}, 10);
i have implemented these in object oriented javascript as follows
function Loader() {
this.jQuery = null;
// check for specifically jQuery 1.8.2+, if not, load it
if (jQuery == undefined) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
} else {
var jQueryVersion = $.fn.jquery;
jQueryVersion = parseInt(jQueryVersion.split('.').join(""));
if (182 > jQueryVersion) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
}
}
}
Loader.prototype.LoadAllFile = function() {
//here i am loading all files
}
Loader.prototype.bindMap = function(options) {
this.LoadAllFile();
//execute the script after loading the files... which we called as myscript
}
i am loading more than 12-14 js files via ajax.
if you observe Loader.prototype.bindMap, i am loading all the files first and then executing the script.
But it seems that myscript the script start executing before all files being loaded.
what are the better ways to execute the script only after all js files are loaded.
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
Based on the documentation on Jquery.getScript , it is a shorthand for Jquery.ajax. By default this in async call. You might want to change it to do a synchronous call.
To set this property, you can refer to this
So instead of doing a setInterval, you can just loop in your array and do a Jquery.getScript.

setTimeout problem with Google Feed API

I have used google feed API to read a Rss feed url and display the title. When I call the function get_rss1_feeds directly It works fine. But when I call it with setTimeout or setInterval I am able to see only blank screen and the page does not stop loading!!
<script src="http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0" type="text/javascript"></script>
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="query.mobile-1.0a4.1.min.js"></script>
<script type="text/javascript" src="jsRss.js"></script>
<script type="text/javascript" src="notification.js"></script>
My notification.js
/** global variable **/
var Rsstitle;
/** end global variable **/
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
// Empty
}
function get_rss1_feeds() {
console.log('test'); // this is being outputted
var Rss1_title = getRss("http://yofreesamples.com/category/free-coupons/feed/?type=rss", function(entry_title) {
if(Rsstitle != entry_title)
Rsstitle = entry_title;
console.log('test1',Rsstitle); // not working
});
}
//get_rss1_feeds() works fine
setTimeout(get_rss1_feeds,5000);
My jsRss.js file
function getRss(url, callback){
console.log('test2'); // this is being outputted
if(url == null) return false;
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
var entry = result.feed.entries[0];
var entry_title = entry.title; // need to get this value
callback && callback(entry_title);
}
}
function Load() {
// Create a feed instance that will grab feed.
var feed = new google.feeds.Feed(url);
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(Load);
}
You need to set a breakpoint in the getRss() function and see what's going on when it's called from setTimeout(). My guess would be that something in that function has a scoping issue and isn't available from the global scope that setTimeout runs in, but is available from the normal scope you tried it in. It could be variables or it could be functions that aren't available.
This can sometimes happen if functions are declared inside another function and thus aren't actually available globally.
FYI, this block of code is very odd:
var Rsstitle;
if(Rsstitle != entry_title)
Rsstitle = entry_title;
You can replace it with this:
var Rsstitle = entry_title;

Categories

Resources