HTML script doesn't wait until previous script is loaded - javascript

I get the testFile.js filename from url parameters, so it is loaded dynamically.
Then i do:
<script>jQuery.getScript('testFolder/testFile.js');</script>
<script src="ok1.js" type="text/javascript" charset="UTF-8"> </script>
<script src="ok2.js" type="text/javascript" charset="UTF-8"> </script>
testFile.js has:
function getFile0(){}
ok1.js has:
function getFile1(){}
function getFile2(){}
function getFile3(){}
ok2.js has:
var _getFiles = [getFile0(), getFile1(), getFile2(), getFile2()];
Although, it is supposed to load first the testFile.js, then ok1.js and finally ok2.js, i get this error for ok2.js: Uncaught ReferenceError: getFile0 is not defined
I have tried plenty of stuff like:
jQuery.getScript('testFolder/testFile.js').done(function() {
jQuery.getScript('ok1.js').done(function() {
jQuery.getScript('ok2.js');
});
});
it is loading without error, but the page is not working as it should.

Related

Difficulties running JavaScript (from .js file) in an Angular application

I am trying to incorporate a Javascript function (contained in app.js), which I am trying to run from the index.html of my Angular 2 application.
Initially I used a CLI program called Office Add-in generator to make a non-angular application, in which this JavaScript works.
However when using the Add-in generator in an Angular application the app.js file is not automatically generated. Manually copy pasting the app.js file and <script> link does not work either. I realise I have only provided a couple of files worth of code, let me know if I should edit more in, or provide a github link?
The error in chrome is net::ERR_ABORTED not defined with a 404 message. (relating to the app.js file)
~~~~HTML~~~~~
<head>
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.components.css">
<meta charset="utf-8">
<title>Microsoft Graph Connect sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
window.history.replaceState = function(){};
window.history.pushState = function(){};
</script>
</head>
<body>
<app-root></app-root>
<button onclick="setItemBody()">Paste to email</button>
<script type="text/javascript" src="node_modules/core-js/client/core.js"></script>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="node_modules/office-ui-fabric-js/dist/js/fabric.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
~~~~~~~app.js~~~~~~~~
var item;
Office.initialize = function () {
item = Office.context.mailbox.item;
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
// Set data in the body of the composed item.
// setItemBody();
});
}
// Get the body type of the composed item, and set data in
// in the appropriate data type in the item body.
function setItemBody() {
item.body.getTypeAsync(
function (result) {
if (result.status == Office.AsyncResultStatus.Failed){
write(result.error.message);
}
else {
// Successfully got the type of item body.
// Set data of the appropriate type in body.
if (result.value == Office.MailboxEnums.BodyType.Html) {
// Body is of HTML type.
// Specify HTML in the coercionType parameter
// of setSelectedDataAsync.
item.body.setSelectedDataAsync(
'<b>These are the times I am available:</b><br>Monday -- 8:30 to 9:00<br>Tuesday -- 1:00 to 5:00<br>Thursday -- 4:00 to 5:00<br>',
{ coercionType: Office.CoercionType.Html,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
else {
// Body is of text type.
item.body.setSelectedDataAsync(
' Kindly note we now open 7 days a week.',
{ coercionType: Office.CoercionType.Text,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
}
});
}
// Writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
Actually you should not just put your js files in index.html better add in .angular-cli.json file.. and about js not working in ng2+ project.. check out https://angular.io/guide/attribute-directives I think you must make wrapper. check this as well https://medium.com/#NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc

javascript module not being found

I have a bunch of web pages where I have an identical construct:
<html>
<head>
<script src="sorttable.js"></script>
<noscript>
<meta http-equiv="refresh" content="60">
</noscript>
<script type="text/javascript">
<!--
var sURL = unescape(window.location.pathname);
function doLoad()
{
setTimeout( "parent.frames['header_frame'].document.submitform.submit()", 60*1000 );
}
function refresh()
{
window.location.href = sURL;
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.replace( sURL );
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.reload( true );
}
//-->
</script>
</head>
<body>
.
.
.
<script type="text/javascript">
window.onload = function() { sorttable.innerSortFunction.apply(document.getElementById("OpenFace-2"), []); doLoad(); }
</script>
</body>
</html>
This works perfectly in every page except for one, where when the onload function runs it cannot find the sorttable code (which is loaded from sorttable.js up at the top). All these pages are part of the same application and are all in the same dir along with the js file. I do no get any errors in the apache log or the js console until that page loads, when I get:
sorttable.innerSortFunction is undefined
I can't see what makes this one page different. Can anyone see what is wrong here, or give me some pointers on how I can debug this further?
The code I pasted in is from the source of the page where it does not work, but it is identical as the pages where it does work.
Looks like on that page the table with id OpenPhace-2 by which you try to sort have no needed class: sortable
The function innerSortFunction of sorttable object will be present only if there is any table with sortable class exists.

cannot change content of div - Uncaught TypeError: Cannot set property 'innerHTML' of null

I would like to change the contents of a div, using javascript and innerHTML.
I cannot get it to work. I just added the code for changing the div, before that the code was working fine. I double checked the syntax.
I'm using webshims, openlayers and jquery/javascript
In the in the console I see
Uncaught TypeError: Cannot set property 'innerHTML' of null
imagegaledit - myFile.php :768
so.onmessage - myFile.php :324
768 is that line
document.getElementById("imgedtitle").innerHTML=mnmi[0];
and 324 is this
imagegaledit(0);
Little help?
Thanks
edit
websockets work and responce fine
Here is the code (concise and simplified)
<!doctype html>
<header>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html">
<script src="jquery-1.8.2.min.js"></script>
<script src="js-webshim/minified/extras/modernizr-custom.js"></script>
<script src="js-webshim/minified/polyfiller.js"></script>
<script>
$.webshims.polyfill();
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--open layers api library-->
<script type='text/javascript' src='OpenLayers.js'></script>
<script type='text/javascript'>
//openlayers vars and stuff here...
function init(){
//when a point on map clicked...
function selected_feature(event){
//some openlayers magic...
var so = new WebSocket("ws://localhost:8000");
so.onerror=function (evt)
{response.textContent = evt;}
so.onopen = function(){
response.textContent = "opened";
so.send(JSON.stringify({command:'map',fmid:jas}));
}
so.onmessage = function (evt) {
var received_msg = evt.data;
var packet = JSON.parse(received_msg);
//pass data to var and arrays...
imagegaledit(0);
}
}//closes function selected_feature
}//closes init
function imagegaledit (w){
if (w==0){
document.getElementById("imgedtitle").innerHTML=mnmi[0];
}
}//closes imagegaledit
</script>
<body onload='init();'>
Title</br><div id="imgedtitle"> </div> </br>
</body>
You need a closing script tag:
</script>
<body>

"Cannot call method 'oEmbed' of null" when embedding Soundcloud player in dynamically generated Div

Using the Soundcloud JavaScript API, I want to dynamically generate a page of player widgets using track search results. My code is as follows:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks,SC)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{to:900000},tags:'hitech',downloadable:true},
function(tracks,SC)
{
makeDivsFromTracks(tracks,SC);
});
</script>
</body>
</html>
When I load this, the SC.oEmbed() call throws an error:
Uncaught TypeError: Cannot call method 'oEmbed' of null
which would seem to indicate that either the divs aren't being generated or the search results aren't being returned, but if I remove the SC.oEmbed() call and replace it with:
newDiv.innerHTML=track.permalink_url;
then I get a nice list of the URLs for my search results.
And if I create a widget using a static div and static URL, e.g.
<body>
<div id="putTheWidgetHere"></div>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.oEmbed("http://soundcloud.com/exampleTrack", {color: "ff0066"}, document.getElementById("putTheWidgetHere"));
</script>
</body>
then that works fine as well. So what's the problem with my oEmbed() call with these dynamically created elements?
Solved it. I took out the SC argument from the callback function and makeDivsFromTracks(), and now all the players show up. Not sure exactly why this works--maybe it has to do with the SC object being defined in the SDK script reference, so it's globally available and doesn't need to be passed into functions?
Anyways, working code is:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
//newDiv.innerHTML=track.permalink_url;
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{from:180000,to:900000},tags:'hitech',downloadable:true},function
(tracks){makeDivsFromTracks(tracks);});
</script>
</body>
</html>

what if jquery.js is include into the page twice?

If I introduce the jquery.js into the page twice(unintentional OR intentional), what will happen?
Is there any mechanism in jquery that can handle this situation?
AFAIK, the later one jquery will overwrite the previous one, and if there is some action binding with the previous one, it will be cleared.
What can I do to avoid the later one overwrite the previous one?
===edited===
I couldn't understand WHY this question got a down vote. Could the people who give the down vote give out the answer?
==edited again==
#user568458
u r right, now it's the test code:
<html>
<head>
</head>
<body>
fast<em id="fast"></em><br>
slow<em id="slow"></em><br>
<em id="locker"></em>
</body>
<script type="text/javascript">
function callback(type){
document.getElementById(type).innerHTML=" loaded!";
console.log($.foo);
console.log($);
console.log($.foo);
$("#locker").html(type);
console.log($("#locker").click);
$("#locker").click(function(){console.log(type);});
$.foo = "fast";
console.log($.foo);
}
function ajax(url, type){
var JSONP = document.createElement('script');
JSONP.type = "text/javascript";
JSONP.src = url+"?callback=callback"+type;
JSONP.async = JSONP.async;
JSONP.onload=function(){
callback(type);
}
document.getElementsByTagName('head')[0].appendChild(JSONP);
}
</script>
<script>
ajax("http://foo.com/jquery.fast.js", "fast");
ajax("http://foo.com/jquery.slow.js", "slow");
</script>
</html>
it produced the result:
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast test:19
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast
the token "$" of the previous one(jquery.fast.js) is overwrite by the later(jquery.slow.js) one.
Is there any method to avoid the overwriting?
I did try this code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#try').click(function() {
alert('ok');
});
});
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<button id="try">Try me</button>
</body>
</html>
Nothing happend. On click I've got an alert. Same result if the second jquery.js loaded in body tag before or after the button.

Categories

Resources