Call .js file from another .js file - javascript

I have one javascript program in my module; say test1.js. It has IF..ELSEIF statements. My challenge is I want to call different .js programs based on conditions in IF-ELSE statements.
TEST1.js looks like -
-----
if(cond1) {
//want to call test2.js here
}
else if(cond2) {
//want to call test3.js here
}
How do I do this in javascript?

if(cond1)
{
//want to call test2.js here
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "test2.js";
document.body.appendChild(js);
}
else if(cond2)
{
//want to call test3.js here
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "test3.js";
document.body.appendChild(js);
}

test1.js
var arr={}; //array
test2.js
function alertOne() {
if(cond1) {
//from test1.js here
alert(arr);
}
else if(cond2) {
}
}
in HTML
<head>
<script src="test1.js" type="text/javascript"></script>
<script src="test2.js" type="text/javascript"></script>
<head>
Use this method.

Related

Call Function from Dynamically loaded Javascript file

I have a base.js file that called from my index.html file and this base.js call script script1.js or script2.js according to parameter passed to the base.js file and then I have another script called editor.js will call a function -with the same name but different implementation- from script1.js or script2.js, so my question is how I execute the function after loading the script1.js or script2.js
Samples of what I mean:
index.html
<html>
<head>
<meta charset="utf-8">
<title>Rich Text Editor</title>
<link rel="stylesheet" type="text/css" href="content/css/app-min.css">
</head>
<body>
<div class="new-question page">
<p>
<textarea id="textBox1" class="html-editor" cols="70" rows="10">
</textarea>
</p>
<p>
<button id="submit">Submit</button>
</p>
</div>
<script type="text/javascript" src="base.js"></script>
<script>
LoadFunction("multiply");
</script>
<script type="text/javascript" src="editor.js"></script>
<script type="text/javascript" src="content/js/script.js"></script>
<script type="text/javascript" src="content/js/custom-script.js"></script>
</body>
</html>
base.js
let LoadFunction = function (type) {
//loading localization script
let script = document.createElement('script');
script.type = 'text/javascript';
document.querySelector('body').appendChild(script );
if(type == "multiply")
script.src = `script1.js`
else
script.src = `script2.js`
}
script1.js
function Calculate(a,b){
return a*b;
}
script2.js
function Calculate(a,b){
return a+b;
}
editor.js
var result = Calculate(5,9);
console.log(result);
Consider reading more about Promises
https://developer.mozilla.org/he/docs/Web/JavaScript/Reference/Global_Objects/Promise
the following is an example using your code,
I don't think it fully do what you're looking for (as I called the loadFunction in the editor.js and not in the main file, but I believe this example + the documentation above will help you get the idea). Good luck :)
base.js
let loadFunction = function (type) {
//loading localization script
let script = document.createElement('script');
script.type = 'text/javascript';
document.querySelector('body').appendChild(script );
if(type == "multiply")
script.src = `script1.js`
else
script.src = `script2.js`
// return a promise
return new Promise((res, rej) => {
script.onload = function() {
res();
}
script.onerror = function () {
rej();
}
});
}
editor.js
loadFunction('multiple')
.then(() => {
// The script file has been loaded.
// We can use the function.
var result = Calculate(5,9);
console.log(result);
})
.catch(() => {
console.error('Could not load the script file.');
});
Haven't fully tested the code.

Ensure load of javascript before proceed

I have following js includes:
<script src="~/js/api/config.js"></script>
<script src="~/js/authentication.js"></script>
<script src="~/lib/es6-promise-polyfill/promise.min.js"></script>
<script>Vue.use(VeeValidate)</script>
<script src="~/js/home.js"></script>
authentication.js has an ajax call. home.js must not be called before authentication and its ajax calls has completed. Is this possible?
You can call the following function from xmlhttp.onreadystatechange event
function loadJS() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = '/js/home.js';
document.getElementsByTagName('head')[0].appendChild(s);
}

how to load main.js only after facebook response status is connected in cocos2d-js

I am using cocos2d-js for game development. In a script of index.html I want to load main.js only when some conditions will be fulfilled.
The sample code is the below
<script>
if(user_id == data.id)
{
// call the main.js
}
</script>
I tried the below
<script>
if(user_id == data.id)
{
(function(document){
var s = document.createElement('script');
s.id = "external_content";
s.async = true;
s.src = "main.js";
document.getElementsByTagName('body')[0].appendChild(s);
s.onload = function() {
document.write(external_content);
}
}(document));
}
</script>
But it does not work. I can not call the main.js from inside another sript. What can I do ? Please help.

What am I doing wrong with this javascript?

I want this simple javascript to display live data from the Cryptsy market. In the fiddle, it works fine, but when I deploy it live, it does not display. I'm new to javascript and coding-beyond-html in general, so I'll greatly appreciate any help!
Deployed: http://bytillionaire.com/HTMLCoin.com/index.html
Fiddle: http://jsfiddle.net/bitillionaire/5fub4mvf/2/
code here:
<head>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function() {
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 10000);
var url = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=458';
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json', function(data) {
jQuery('#ticker').html(data['query'].results.json.return.markets.HTML5.lasttradeprice);
jQuery('#ticker').append(' ' + data['query'].results.json.return.markets.HTML5.secondarycode);
});
}
}); //]]>
</script>
</head>
<body>
<div id="navigation">
Follow #htmlcoin
<script>
! function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
p = /^http:/.test(d.location) ? 'http' : 'https';
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = p + '://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js, fjs);
}
}(document, 'script', 'twitter-wjs');
</script>
<div id="ticker"></div>
</div>
</body>
I see an error at your site in console Uncaught ReferenceError: $ is not defined
it looks like jQuery is not defined
You haven't included jQuery on your page!
You dont have jQuery in your webpage.
Add this in the of your HTML code and it should be before other scripts:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Source
Make sure to always have a copy of jquery.js in your javascript folder and to call it!
In
<script src="js/jquery.js"></script>
This will ensure that jquery functions are able to run.

how to ensure sequential order of this javascript?

To begin my page i do a check with facebook to get the login status of the user. I then create a namespace within the window object for use in other javascript files. Before I load any other javascript i need this namespace to be created, or else it will be undefined when i try to access it. Sometimes it completes first, and sometimes it does not. How can i make sure that it happens correctly every time?
.
.
.
FB.getLoginStatus(function(response) {
// store data on the user inside of a namespace
// inside of the window object so it can be accessed
// from anywhere. Use this like '$_SESSION'
console.log('doing it');
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
})
};
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document))
</script>
<!-- Load the script "js/main.js" as our entry point for require -->
<script data-main="js/main" src="lib/Require/require.js"></script>
specifically, i need the:
<script data-main="js/main" src="lib/Require/require.js"></script>
to not happen until the facebook function is complete
Move the code relying on the namespace into the Facebook callback. If it's the <script data-main="js/main" src="lib/Require/require.js"></script>, create the script element dynamically:
// ...
FB.getLoginStatus(function(response) {
// store data on the user inside of a namespace
// inside of the window object so it can be accessed
// from anywhere. Use this like '$_SESSION'
console.log('doing it');
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
// Create the script element when ready
var script = document.createElement('script');
script.setAttribute("data-main", "js/main");
script.src = "lib/Require/require.js";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
// Or instead of `document.getElementsByTagName('script')[0].parentNode`
// you can use `document.documentElement` or `document.getElementsByTagName('head')[0]
// or a few others
})
};
You could move it all to one place as TJ suggests. Or you could check to see if your variable is created before attempting to run your own code:
// First this:
FB.getLoginStatus(function(response) {
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
});
// Later in the code:
(function () {
var isFBLoaded = function () {
// If FB has loaded - run our code
if (window.easyUserData) {
myOtherFBStuff();
}
// If not - check again in 500 ms
else {
setTimeout(isFBLoaded, 500);
}
};
var myOtherFBStuff = function () {
// do stuff here
};
isFBLoaded();
})();

Categories

Resources