I really can't figure out how to do it. I need to call somefunc() from file.js file on page load.
My file.js contains:
function somefunc() {
pc.somefunc(gotLocalDescription,
function(error) {
console.log(error)
}, {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
});
}
// Socket.io
var socket = io.connect('', {
port: 1234
});
function sendCall(call) {
socket.emit('call', call);
}
socket.on('call', function(call) {
if (call.type === 'offer') {
pc.setRemoteDescription(new SessionDescription(call));
createAnswer();
} else if (call.type === 'answer') {
console.log('10--if call type is answer');
pc.setRemoteDescription(new SessionDescription(call));
} else if (call.type === 'candidate') {
var candidate = new IceCandidate({
sdpMLineIndex: call.label,
candidate: call.candidate
});
pc.addIceCandidate(candidate);
}
});
consider using
Trigger
instead
You can simple call the function which is in another file.
Have created a plunker.Also note it has a seperate file file.js. If you using name spacing please take care of that.
Click Me
WORKING COPY
You can use this:
click
But first you must include file.js in you html
<script type="text/javascript" src="file.js">
Using window.onload (pure javascript), you can call your somefunc() of file.js on page load, as following:
function somefunc() {
alert('somefunc() of file.js called!');
/*
* Your logic goes here.
*/
}
window.onload = somefunc();
DEMO
While, if you want to use jQuery, then include jquery source first and then your custom script file containing your method and DOM ready call, as following:
function somefunc() {
alert('somefunc() of file.js called!');
/*
* Your logic goes here.
*/
}
jQuery(document).ready(function(){
somefunc();
});
// OR
jQuery(function({
somefunc();
});
First make sure you have included your file.js to head of your html and the location to file is correct.
Related
(simplification) I have two javascript files I want to include. They inter-link each other.
Problem: If I just include them the following there is an error because source1.js needs something from source2.js and vice-versa.
How can I include inter-linking source files properly in HTML, without merging them? (Imaging various already-large files)
<head>
<script src="source1.js"></script>
<script src="source2.js"></script>
source1.js
function filtersomething() {
...
othersource.somefunction();
}
source2.js
var columns = {
text: filtersomething()
}
Added more to a working snippet. I'd use that code over some of the examples here. it deals more with arguments, promises, etc. Have to run, hope this helps.
You can place an event listener within each JS file, which would not call any functions until the dom is loaded. Doing this allows both JS files to load in and see the others functions available.
// script.js
window.addEventListener('DOMContentLoaded', (event) => {
filtersomething();
});
function filtersomething() {
...
othersource.somefunction();
}
Because these are loaded after script.js, script2.js always sees what script.JS has available. So, script.JS does not see what script2.JS has until after it is loaded
// script2.js
window.addEventListener('DOMContentLoaded', (event) => {
var columns = {
text: filtersomething()
}
});
We can also watch for a pointer, as suggested. This is useful when waiting for jQuery to load as well. So within your script files, watch for a property to be set, then execute.
<head>
<script>
function deferRun(thisMethod, scriptNum) {
if (window[scriptNum])
return thisMethod();
// No property found, set timeout of 50ms and try again
setTimeout(function() { defer(thisMethod, scriptNum) }, 50);
}
</script>
<script src="source1.js"></script>
<script src="source2.js"></script>
</head>
// script2.JS
// wait until script.js is available, then return result
var columns = {
text: deferRun(filtersomething, 'script1')
}
// Set our window property saying script loaded
window.script2 = true;
//script.js
function filtersomething() {
...
deferRun(othersource.somefunction, 'script2');
}
// Set our window property saying script loaded
window.script1 = true;
// Think of script1/script2 as <script> tags.
window.script1 = {
// script.js
filtersomething: () => {
return deferRun('somefunction', 'script2', 'message to use');
}
};
// Now "load" script2.js
window.script2 = {
somefunction: (msg) => {
return `msg response is ${msg}`
},
columns: {
// wait until script.js is available, then return result
text: deferRun('filtersomething', 'script1')
},
render: async() => {
console.log(await window.script2.columns.text);
}
};
(async() => {
await window.script2.render();
})();
<head>
<script>
// this is available to all and before either script 1 or 2 loads
function deferRun(thisMethod, property, argument = null) {
if (window[property])
return window[property][thisMethod](argument);
// No property found, set timeout of 50ms and try again
return setTimeout(function() {
deferRun(thisMethod, property, argument)
}, 50);
}
</script>
</head>
You can place an event listener within each JS file, which would not call any functions until the dom is loaded. Doing this allows both JS files to load in and see the others functions available.
<pre>
// script.js
window.addEventListener('DOMContentLoaded', (event) => {
filtersomething();
});
function filtersomething() {
...
othersource.somefunction();
}
```
Because these are loaded after script.js, script2.js always sees what script.JS has available. So, script.JS does not see what script2.JS has until after it is loaded
```js
// script2.js
window.addEventListener('DOMContentLoaded', (event) => {
var columns = {
text: filtersomething()
}
});
```
We can also watch for a pointer, as suggested. This is useful when waiting for jQuery to load as well. So within your script files, watch for a property to be set, then execute.
</pre>
I'm using NightwatchJS with NodeJS: http://nightwatchjs.org/api
I have a modal dialog, which may or may not appear. It has a #close_button that needs to be clicked (if the modal does appear) to continue.
I set the abortOnFailure parameter of waitForElementPresent to false so the script continues if the modal does not appear. However I can't get it to work.
Any suggestions?
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false, function() {
this.click('#close_button')
})
.setValue('#username', 'test#email.com')
//more code here
.end(); //does end() go here or inside .waitForElementPresent() above?
}
}
abortOnFailure works fine, however waitForElementPresent has a bug now in which the callback you passed it's not called in the correct context. That will be fixed.
In the mean time you can write your test like this, with placing the click outside, which is the same thing and looks cleaner:
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false)
.click('#close_button')
.setValue('#username', 'test#email.com')
//more code here
.end(); // end() goes here
}
}
I ran into something similar, I was waiting for an iframe to be present. I created a function to actually close it:
pageObject function:
Home.prototype.closeIframe = function(browser) {
var self = this;
console.log('Checking for iframe');
this.browser
.isVisible(iframeSelectors.iframe, function(result) {
if (result.value === true) {
self.browser
.log('iframe visible')
.frame(iframeSelectors.name)
.waitForElementVisible(iframeSelectors.closeLink)
.click(iframeSelectors.closeLink)
.assert.elementNotPresent(iframeSelectors.iframe)
.frame(null)
.pause(2000); //allow for proper frame switching
} else {
console.log('iframe is not visible');
}
});
return this;
In my test I wait for the page to fully load before executing the above function.
Using jQuery the following would log that the app had loaded once the DOM and all assets had been downloaded by the browser:
$(window).load(function() {
console.log('app loaded');
});
However I don't want this check to happen until after some other things have run.
So for example:
function checkLoaded()
{
$(window).load(function() {
console.log('app loaded');
});
}
So let's say I call this function after a bunch of other functions.
The problem is, because $(window).load(function() is an event listener, when I call the checkLoaded() function the event won't ALWAYS run (because it MAY have already been fired because everything has downloaded BEFORE the checkLoaded() function has run).
Any ideas on how I can do this?
I tried this:
function checkLoaded()
{
if(loaded)
{
console.log('app loaded');
}
else
{
checkLoaded(); // keep checking until the loaded becomes true
}
}
$(window).load(function(){
loaded = true;
});
But the problem here is that the checkLoaded function COULD get called hundreds of times in a few seconds and isn't a nice way of handling this.
UPDATE: The function is called using checkLoaded(); Just so everyone knows I am calling the function!
UPDATE 2:
The plan is essentially this:
function init() {
start();
}();
function start() {
// Show Preloader... and other stuff
/// Once all logic has finished call checkLoaded
checkLoaded();
}
function checkLoaded() {
if(loaded) {
show();
}
}
function show() {
... // show app
}
So I should be able to know if the status of loaded is true, but keep checking until it becomes true as it may be true or false when I get to the checking stage.
You run it either on window load or if it's already done using such kind of code:
function onLoad(loading, loaded) {
if (document.readyState === 'complete') {
return loaded();
}
loading();
if (window.addEventListener) {
window.addEventListener('load', loaded, false);
} else if (window.attachEvent) {
window.attachEvent('onload', loaded);
}
}
onLoad(function() {
console.log('I am waiting for the page to be loaded');
}, function() {
console.log('The page is loaded');
});
var loaded=false;
$(window).load(function() {
loaded=true;
});
function checkLoaded()
{
// do something if loaded===true
}
Try this
function checkLoaded()
{
$(window).load(function() {
console.log('app loaded');
});
}
checkLoaded();
you want to make checkLoaded block and thats a bad idea:
javascript has no threads and blocking like that will just burn CPU while potentially blocking the whole script.
don't wait like you do for loaded to be to true. use the eventhandler as it is meant to be used.
maybe give checkLoaded a parameter to a function you want called:
function checkLoaded(continueWhenLoaded) {
$(window).load(function() {
continueWhenLoaded();
});
}
Have you looked into a solution involving jQuery's .promise() and .done()? Look at some of the examples in the documentation, it might be what you are looking for.
It seems that helloworld.js gets loaded multiple times based on the number of times I click #load. I say this because when I look at Google Chromes Developer Tools Network tab, it shows helloworld.js as many times as I click #load.
$(document).ready(function() {
$("#load").click(function(){
$.getScript('helloworld.js', function() {
hello();
});
});
});
The hello() function looks like this:
function hello(){
alert("hello");
}
Is it possible to detect if helloworld.js has already loaded?
So if it hasn't loaded, load it, and if it has loaded, don't load it.
This is what Developer Tools currently shows me if I click the #load button 4 times:
Set a flag when file loaded successfully. If flag is set then skip the file loading again.
Try this code,
var isLoaded = 0; //Set the flag OFF
$(document).ready(function() {
$("#load").click(function(){
if(isLoaded){ //If flag is ON then return false
alert("File already loaded");
return false;
}
$.getScript('helloworld.js', function() {
isLoaded = 1; //Turn ON the flag
hello();
});
});
});
So why not only fire the event once like this:
$("#load").one("click", function() {
$load = $(this);
$.getScript('helloworld.js', function() {
hello();
// bind hello to the click event of load for subsequent calls
$load.on('click', hello);
});
});
That would prevent subsequent loads and avoids the use of a global
Another option is letting .getScript() run but let it take the script from browser's cache so you won't have it reloaded each and every time.
To achieve this, add such code:
$.ajaxSetup({
cache: true
});
This is taken from the documentation page.
You could create a helper function:
var getScript = (function() {
var loadedFiles = {};
return function(filename, callback) {
if(loadedFiles[filename]) {
callback();
} else {
$.getScript(filename, function() {
loadedFiles[filename] = true;
callback();
});
}
};
})();
I am writing a Chrome extension that needs to be able to add code into the web page it is viewing. Right now in my background page I have:
chrome.tabs.onUpdated.addListener(function(tabId, info) {
if (info.status=="complete") {
chrome.tabs.executeScript(null, {file: "injectme.js"})
}
})
and the injected script injectme.js which contains a function that looks like this:
function() {
if (!document.getElementById('searchforme')) {
x=document.createElement('script')
x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
x.setAttribute('id','searchforme')
document.appendChild(x)
alert('it is finished')
} else {
alert('so close')
}
}
My question is how do I call this function the moment it loads so it can insert the script into a web page?
If I understood you :)
All you need to do is to warp you current function inside something like:
(function () {
// your code
if (!document.getElementById('searchforme')) {
x=document.createElement('script')
x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
x.setAttribute('id','searchforme')
document.appendChild(x)
alert('it is finished')
} else {
alert('so close')
}
}());
so it will be an 'immediate invocation' function.