MathJax local extension loading time - javascript

I am using local version of both mhchem and arabic extensions for mathjax as I need to add some extra functions to arabic extensions and I am loading mathjax from https://cdn.mathjax.org/mathjax/latest/MathJax.js, my problem is when I load the extensions from local server it takes around 15sec to fully loaded and it gave an error File failed to load: http://127.0.0.1:8887/HTMLEditor/MathJax/mhchem/mhchem.js but both extensions working properly! and if I changed the MathJax.Ajax.config.path to get from https://cdn.mathjax.org/mathjax/contrib it loads fast in less than a second without any errors.
I tried to stop loading of arabic extension to see if my edits cause an issue but I got the same result
Sample of my HTML (Note: I expect that it will not work for you because I load some of scripts and extensions from local server and that exactly my issue)
<html>
<head>
<!-- <script src="arabic_mathjax.jsx"></script> -->
<script>
window.MathJax = {
jax: ["input/TeX", "output/HTML-CSS"],
extensions: ["tex2jax.js", "[Contrib]/arabic/arabic.js", "[Contrib]/mhchem/mhchem.js"],
TeX: {
extensions: ["AMSmath.js", "AMSsymbols.js", "autoload-all.js"]
},
'HTML-CSS': {
undefinedFamily: 'Amiri'
},
tex2jax: {
inlineMath: [
['$', '$'],
["\\(", "\\)"]
],
processEscapes: true
},
AuthorInit: function() {
MathJax.Hub.Register.StartupHook("Begin", function() {
MathJax.Ajax.config.path["Contrib"] = "http://127.0.0.1:8887/HTMLEditor/MathJax";
// your code to run once MathJax is ready, e.g., custom extensions etc.
MathJax.Hub.Queue( function(){
// something to queue after the initial typesetting is done
}
);
});
}
};
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function() {
// remote script has loaded
};
script.src = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
FixArabicCharacters($('.container'))
});
function FixArabicCharacters(node) {
if ($(node).children().length > 0) {
$(node).children().each(function () {
FixArabicCharacters(this);
});
}
else {
var str = $(node).text()
var regex = new RegExp("([\\u0621-\\u064A\\u0660-\\u0669])", "gm");
if (str.toLowerCase().indexOf('<math style="displayed">') >= 0) {
if (regex.test($(node).text())) {
$(node).html("$$\\alwaysar{" + $(node)
.text().replace('$', '').replace('<math style="displayed">', '').replace('</math>', '')
.replace(regex, "\\fliph{\\text{$1}}") + "}$$");
}
}
if (str.toLowerCase().indexOf('<math>') >= 0) {
if (regex.test($(node).text())) {
$(node).html("$\\alwaysar{" + $(node)
.text().replace('$', '').replace('<math>', '').replace('</math>', '')
.replace(regex, "\\fliph{\\text{$1}}") + "}$");
}
}
}
}
</script>
</head>
<body>
<p>input:</p>
<input type="text" id="myid" oninput="DynamicMJ.update()">
<p class="container" id="test"></p>
<!-- <p><input type="button" value="Update" onclick="" /></p> -->
<script>
var DynamicMJ = {
formula: document.getElementById("test"),
update: function () {
var a = document.getElementById("myid").value;
this.formula.innerHTML = "\\[" + a + "\\]";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.formula]);
}
};
DynamicMJ.update();
</script>
</body>
</html>
So please tell me, am I miss something?

Related

Calling external JavaScript function in full stack app

I have used JavaScript for a while, but am brand new to Node.js and full stack development, taking on a small project as a hobbyist. I have Heroku set up to host the app at https://midi-writer.herokuapp.com/ and am able to edit my files and update the app (using git commands) through my Mac terminal.
I am having trouble figuring out how to call a JavaScript function in an external file (in /src/js/midiWriter.js) from the index.html page. Using <script type="text/javascript" src="bundle.js"></script> doesn't work (I think that the file is 'bundled' when I push it to Heroku), and I have also tried <script type="text/javascript" src="../src/js/midiWriter.js"></script>
Here is the full code for index.html with the function call at the end of the script.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Heart Beats</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="bundle.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"></link>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
<fieldset>
<h2>EKG File</h2>
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
<hr>
Frequency: <div id="frequency"></div>
Metadata:<div id="metaData"></div>
<div id="midiDownload">A link will appear here after the file has been processed</div>
</fieldset>
</form>
<script type="text/javascript">
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
var metaDataString = '';
document.getElementById("frequency").innerHTML = newArr.frequency + " Hz";
for (i = 0; i < newArr.meta.dashboard_measurements.length; i++){
metaDataString += newArr.meta.dashboard_measurements[i].description + ": "
+ newArr.meta.dashboard_measurements[i].value
+ " " + newArr.meta.dashboard_measurements[i].unit + "<br>";
}
document.getElementById("metaData").innerHTML = metaDataString;
}
midiWriter();
}
</script>
</body>
</html>
Here's the midiWriter.js file:
function midiWriter(){
var MidiWriter = require('midi-writer-js');
var track = new MidiWriter.Track();
track.addEvent([
new MidiWriter.NoteEvent({pitch: ['E4','D4'], duration: '4'}),
new MidiWriter.NoteEvent({pitch: ['C4'], duration: '2'}),
new MidiWriter.NoteEvent({pitch: ['E4','D4'], duration: '4'}),
new MidiWriter.NoteEvent({pitch: ['C4'], duration: '2'}),
new MidiWriter.NoteEvent({pitch: ['C4', 'C4', 'C4', 'C4', 'D4', 'D4', 'D4', 'D4'], duration: '8'}),
new MidiWriter.NoteEvent({pitch: ['E4','D4'], duration: '4'}),
new MidiWriter.NoteEvent({pitch: ['C4'], duration: '2'})
], function(event, index) {
return {sequential: true};
}
);
var write = new MidiWriter.Writer(track);
console.log(write.dataUri());
var app = document.getElementById('midiDownload');
var downloadLink = `Download Link`;
app.innerHTML = downloadLink;
}
I get the Uncaught Reference Error "midiWriter is not defined" with this version.
Please excuse any lame errors! I am brand new to this :)
Simple solution would be like this:
In your html file:
<script src="../src/js/midiWriter.js"></script>
<script>
...
midiWriter();
</script>
What the first line does is set the source of the file you will use and the in the plain script tags, you can use any function or variable that has global scope and is declared in the file whose path you declared in the <script src=""> tag.
Just hired someone on Fiverr to take a look. The problem is that I need to define the external function globally using window.midiWriter = function (){...

Selenium IDE is stopping javascript

When using Selenium IDE to record actions on a web page the application is stopping the JavaScript and displays the error message "too much recursion."
I'm using Selenium IDE 2.9.1.1 on FireFox 54.0.1
I wrote a simple javascript alert for testing, but it is also being stopped by Selenium.
<html>
<head>
<script>
function hello(){
alert("Hello\nHow are you?");
}
</script>
</head>
<body>
<input type="button" onclick="hello();" value="Say Hi" />
</body>
</html>
enter image description here
selenium-ide/content/recorder.js
Recorder.prototype.reattachWindowMethods = function() {
var window = this.getWrappedWindow();
//this.log.debug("reattach");
if (!this.windowMethods) {
this.originalOpen = window.open;
}
this.windowMethods = {};
['alert', 'confirm', 'prompt', 'open'].forEach(function(method) {
this.windowMethods[method] = window[method];
}, this);
var self = this;
window.alert = function(alert) {
self.windowMethods['alert'].call(self.window, alert);
self.record('assertAlert', alert);
}
}
This is because the function calls are actually being overridden at runtime by Selenium’s own JavaScript.
Add below Javascript code to selenium core user extension, after restart can fix this problem.
//http://docs.seleniumhq.org/docs/08_user_extensions.jsp
Selenium.prototype.doExecute = function(script) {
this.browserbot.getCurrentWindow().eval(script);
};
Selenium.prototype.getExecute = function(script) {
return this.browserbot.getCurrentWindow().eval(script);
};
Selenium.prototype.getJqMethod = function(selector, method) {
return this.getExecute('$("' + selector + '").' + method + '();');
};
Selenium.prototype.getJqText = function(selector) {
return this.getJqMethod(selector, "text");
};
Selenium.prototype.getJqHtml = function(selector) {
return this.getJqMethod(selector, "html");
};
Selenium.prototype.getJqVal = function(selector) {
return this.getJqMethod(selector, "val");
};
PageBot.prototype.locateElementByJq = function(selector, inDocument) {
// FF/Chrome/IE9+: defaultView, OldIE: parentWindow
return (inDocument.defaultView || inDocument.parentWindow)
.eval("jQuery('" + selector.replace(/'/g, "\\'") + "')[0];");
};

Angular.js: Error: Module 'MyApp' is not available

I would like to use this plunk locally on my machine. However, when I either run it with the local Python server or http-server, I keep getting the following Error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
My html file looks like this:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<script scr="main.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.1/papaparse.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/1.1.5/angular-file-upload.min.js"></script>
<link rel="stylesheet" href="main.css">
</head>
<body ng-controller="MyCtrl">
<h1>CSV</h1>
<div>
<input type="checkbox" ng-model="append">
Append to existing on drag & drop
</div>
<div class="drop-container" nv-file-drop nv-file-over uploader="uploader">
<textarea ng-model="csv" placeholder="Enter your CSV here, or drag/drop a CSV file"></textarea>
</div>
<h1>D3 Flare JSON</h1>
<div>
<input type="checkbox" ng-model="compact"> Compact
</div>
<div>
<input type="text" ng-model="tags.parent" placeholder="parent tag">
<input type="text" ng-model="tags.children" placeholder="children tag">
<input type="text" ng-model="tags.leaf" placeholder="leaf tag">
<input type="text" ng-model="tags.size" placeholder="size tag">
</div>
<textarea readonly ng-model="json"></textarea>
</body>
</html>
And the main.js file looks like this:
CSV to D3 Flare JSON converter in AngularJSPreview Edit Code
index.html
main.js
main.css
main.js
angular.module('myApp', ['angularFileUpload'])
.factory('FlareJson', ['$q', function($q) {
function updateTree(curr, arr, tags) {
if ((arr.length || 0) < 2) {
return;
}
if (!curr.hasOwnProperty(tags.children)) {
curr[tags.children] = [];
}
var elem;
if (arr.length == 2) {
elem = {};
elem[tags.leaf] = arr[0];
elem[tags.size] = arr[1];
curr[tags.children].push(elem);
} else {
curr[tags.children].some(function(e) {
if (e[tags.parent] == arr[0] || e[tags.leaf] == arr[0]) {
elem = e;
return true;
}
});
if (!elem) {
elem = {};
elem[tags.parent] = arr[0];
curr[tags.children].push(elem);
}
updateTree(elem, arr.slice(1), tags);
}
}
function buildJson(csv, compact, tags) {
var deferred = $q.defer();
var result = {};
result[tags.parent] = 'flare';
Papa.parse(csv, {
header: false,
dynamicTyping: true,
complete: function(csvArray) {
csvArray.data.forEach(function(line) {
if (line.length) {
updateTree(result, line, tags);
}
});
if (compact) {
deferred.resolve(JSON.stringify(result));
} else {
deferred.resolve(JSON.stringify(result, null, 2));
}
}
});
return deferred.promise;
}
return buildJson;
}])
.controller('MyCtrl', ['$scope', 'FileUploader', 'FlareJson',
function($scope, FileUploader, FlareJson) {
$scope.csv = "";
$scope.compact = false;
$scope.json = "";
$scope.tags = {
parent: 'skill',
children: 'children',
leaf: 'name',
size: 'level'
};
$scope.uploader = new FileUploader();
$scope.uploader.onAfterAddingFile = function(fileItem) {
var reader = new FileReader();
reader.onloadend = function(event) {
$scope.$apply(function() {
if ($scope.append) {
$scope.csv += event.target.result;
} else {
$scope.csv = event.target.result;
}
});
};
reader.readAsText(fileItem._file);
};
function update() {
FlareJson($scope.csv, $scope.compact, $scope.tags).then(function(json) {
$scope.json = json;
});
}
$scope.$watchGroup(['csv', 'compact'], update);
$scope.$watchCollection('tags', update);
}]);
I don't understand what I'm doing wrong. I already searched for similar error messages, but nothing that I found could help me to solve my problem.
You load your script file before angularjs file that's why you are getting this error.
So, Add your "main.js" file after "angular.js" file.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script scr="main.js"></script>
I believe it's because you're loading your main.js before you load Angular. Try putting your script at the end of the script definitions:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.1/papaparse.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/1.1.5/angular-file-upload.min.js"></script>
<script scr="main.js"></script>
Oh, solved! Turns out, that the following couple of first lines in main.js were causing the trouble:
CSV to D3 Flare JSON converter in AngularJSPreview Edit Code
index.html
main.js
main.css
main.js
I removed them from main.js, now it works - yuhuu! :)

document.write alternativ without overwriting the DOM / side

got a problem with the usage of
document.write()
i want to overwrite a div in which a adbanner is loaded and i cant find any solution to this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
var i = 0;
var newImage;
function refresh() {
i++;
if (i >= 5) {
writeAd();
i = 0;
}
}
function writeAd() {
var arr = box1.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML)
}
</script>
</head>
<body
<h1>Bilder Random</h1>
<input type="button" onclick="refresh()" value="go!" />
<div id="box1" class="superbanner">
<table cellspacing="0" cellpadding="0" border="0" class="ad1">
<script language="JavaScript">
if (typeof (WLRCMD) == "undefined") {
var WLRCMD = "";
}
if (typeof (adlink_randomnumber) == "undefined") {
var adlink_randomnumber = Math
.floor(Math.random() * 1000000)
}
document
.write('<scr'
+ 'ipt language="JavaScript" src="http://ad.de.doubleclick.net/adj/oms.skol.de/localnews_bilder;oms=localnews_bilder;reg=;nielsen=3b;dcopt=ist'
+ WLRCMD + ';sz=728x90;tile=1;ord='
+ adlink_randomnumber + '?"><\/scr'+'ipt>');
</script>
</table>
</div>
</body>
</html>
My main problem is the document.write() in the adbanner script part.
i can reload the page with 5 clicks on the button but it overwrites the whole DOM
is there any possability to use something else than document.write()
to insert the adbanner at the beginning of the page load and when calling
the function writeAd()?
This is how you should load JS files dynamically:
if (window.isReady) { //after page was loaded, we must manually add new SCRIPT tag into HEAD
var script = document.createElement('script'), head = document.head || document.getElementsByTagName('head')[0];
script.type = 'text/javascript';
script.src = fileName;
head.appendChild(script);
}
else { //otherwise we are still in a progress of creating HEAD or BODY and we can simply write into document
var write = 'write'; //prevents JSlint from saying that document.write is evil ;)
document[write]('<script type="text/javascript" src="' + fileName + '"></script>');
}
To detect if window is loaded:
window.onload = function() { window.isReady = true; }

Unity Web Player does not work inside .xhtml

when i try to use javascript to start the unity webplayer inside a xhtml-file the webpage cant detect the webplayer and asks me to download it.
Same source(generated by unity itself) with .html works fine
why? :O
<script type='text/javascript' src='https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/jquery.min.js'></script>
<script type="text/javascript">
<!--
var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
if (document.location.protocol == 'https:')
unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
-->
</script>
<script type="text/javascript">
<!--
var config = {
width: 512,
height: 260,
params: { enableDebugging:"0" }
};
var u = new UnityObject2(config);
jQuery(function() {
var $missingScreen = jQuery("#unityPlayer").find(".missing");
var $brokenScreen = jQuery("#unityPlayer").find(".broken");
$missingScreen.hide();
$brokenScreen.hide();
u.observeProgress(function (progress) {
switch(progress.pluginStatus) {
case "broken":
$brokenScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$brokenScreen.show();
break;
case "missing":
$missingScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$missingScreen.show();
break;
case "installed":
$missingScreen.remove();
break;
case "first":
break;
}
});
u.initPlugin(jQuery("#unityPlayer")[0], "BulletImages.unity3d");
});
-->
</script>
<div id="unityPlayer">
<div class="missing">
<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
</a>
</div>
</div>
JavaScript isn't allowed to use document.write() on XHTML pages.
Note the offending snippet:
<script type="text/javascript">
<!--
var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
if (document.location.protocol == 'https:')
unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
-->
</script>
You may notice the script in question is performing a very simple operation. If you know your deployment, you can strip it and include the result plainly:
If deploying to HTTP website:
<script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js"></script>
If deploying to HTTPS website:
<script type="text/javascript" src="https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js"></script>
If you're not sure, an ideal fix would be to edit the page's DOM, but a quick and dirty workaround is to edit a node's innerHTML directly.

Categories

Resources