Unable to dynamically import TensorFlow.js - javascript

I am trying to dynamically import TensorFlow.js using the import function. However, I always receive a TypeError: t is undefined error. The following code is a simple HTML file which recreates the error.
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
import("https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.0.0/dist/tf.min.js")
.then(tf => { console.log(tf); });
</script>
</body>
</html>
Please note that I also desire to dynamically create the code that will use the TensorFlow.js library. Any help on how to dynamically import TensorFlow.js in the browser and run dynamically created code that uses its functions is much appreciated. Below is code that acts similarly to my end goal.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
let code = `import("https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.0.0/dist/tf.min.js").then(tf => {
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
model.predict(tf.tensor2d([5], [1, 1])).print();
// Open the browser devtools to see the output
});
});
`;
let script = document.createElement("script");
script.type = "text/javascript";
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);
</script>
</body>
</html>

You could very well just add the script element dynamically ?
const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.0.0/dist/tf.min.js";
el.onload = (() => {
const script = document.createElement('script');
script.innerHTML = "console.log(tf)";
document.body.appendChild(script);
})();
document.body.appendChild(el);
Alternative
you could also append the script earlier, but do not execute until tf is loaded
example is
const script = document.createElement('script');
script.innerHTML = `
function someDependentCode() {
console.log(tf);
// put all dependent code string here
}
`;
document.body.appendChild(script); //code is added but not called
const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.0.0/dist/tf.min.js";
el.onload = someDependentCode(); //dependent code can now execute
document.body.appendChild(el);

Related

How to run a JS Function in HTML5

How can I run my function "title()" in HTML?
I have created a "main.js" File, in there, there is following Code:
"use strict";
document.addEventListener("DOMContentLoaded", function() {
let newScript = document.createElement("script");
newScript.src = "javascript/head.js";
let heads = document.getElementsByTagName("head")[0];
console.log(heads)
heads.prepend(newScript);
});
in the "main.js" File load an another Script which is called "head.js" and here is the Code of this File:
function title(titleName) {
let title = document.createElement("title");
document.title = titleName;
document.head.appendChild(title);
}
Maybye you need my HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="javascript/main.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script> title("Framework"); </script>
</head>
<body>
</body>
</html>
in head.js add:
window.addEventListener("load", () => title("my desired title name"));
Not sure why someone downvoted, but to clarify, you can run this code anywhere so long as the head.js file has been loaded, it doesn't have to be directly in head.js.
You can add it into main.js:
let newScript = document.createElement("script");
newScript.addEventListener("load", () => title("my desired title name"));
newScript.src = "javascript/head.js";
// ...
You can also run it directly in the HTML in a <script> tag but you'll have to ensure the script is loaded first.

Struggling with installation RxJS ( VS code )

I've created index.html, attached to it script.js and installed RxJS with npm install rxjs. But there are a lot of issues with that
This is what console writes when I comment out my imports statements
And this is when I use import in script.js
Updated: I have linked
<script src="https://unpkg.com/rxjs#6.5.3/bundles/rxjs.umd.min.js"></script>
to the html, but it didn't work out
Check for the files on GitHub
Ok, i figured it out.
this should be your html (make sure that your cdn math is the right path)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/rxjs#6.5.3/bundles/rxjs.umd.min.js"></script>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
and this is your js code:
const { of, fromEvent } = rxjs;
const { map, pluck, mapTo } = rxjs.operators;
const keyup = fromEvent(document, 'keyup');
const keycode = keyup.pipe(
map( event => event.code )
);
const keycodePluck = keyup.pipe(
pluck('code')
);
const pressed = keyup.pipe(
mapTo('Key pressed!')
);
pressed.subscribe(console.log);

Array methods inside HTML

I'm trying to make a very simple html document with some vanilla JavaScript to sort some elements in it.
I've been able to use .map() to print all the elements of an array, but I'd like to include them in html elements. For example. using an <h1> or a <p>.
This is the code I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body onload="mapping()">
<h1>
<script>
const array = [1, 2, 3];
function mapping() {
array.map(arrayItem => {
document.write(arrayItem)
})
}
</script>
</h1>
</body>
</html>
How can I include HTML inside the script, so I can do something with each one of those returned elements? I mean, something like this:
<script>
const array = [1, 2, 3];
function mapping() {
array.map(arrayItem => {
<h1>document.write(arrayItem)</h1>
})
}
</script>
This should work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body onload="mapping()">
<script>
const array = [1, 2, 3];
function mapping() {
array.forEach(arrayItem => {
var newEle = document.createElement('h1');
newEle.innerHTML = arrayItem;
document.body.appendChild(newEle);
});
}
</script>
</body>
</html>
I guess what you want to do is something like this:
<div>
<script type="text/javascript">
document.write("<h1>Main title</h1>")
</script>
</div>
You might want to consider checking the documentation for Javascript at the link I provided. It gives a lot of useful examples and methods. I took the snippet code from there.Hope it helps.

why bindCallback is not a function?

Hi I am using this rxjs libraray .I am getting this error
Rx.Observable.bindCallback is not a function
here is my code
http://jsbin.com/tuxucotake/edit?html,js,console,output
I am reading doc from here
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html
var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
result.subscribe(x => console.log(x), e => console.error(e));
You are using RXJS 4 but the docs you have linked to are RXJS 5
Based on #Günter Zöchbauer answer, bindCallback() is not anymore part of Observableso the correct usage for current version of RxJs (6) would be:
jsbin
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<title>JS Bin</title>
</head>
<body>
</body>
</html>
js
var getJSONAsObservable = rxjs.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('https://mysafeinfo.com/api/data? list=englishmonarchs&format=json');
result.subscribe(
([data,textStatus,jqXhr]) => console.log(data),
e => console.error(e));
Respectively for node:
const Rx = require('rxjs')
const {bindCallback} = Rx;
var getJSONAsObservable = bindCallback(jQuery.getJSON);
....

Firefox not executing JavaScript files that were loaded dynamically

I'm trying to load two scripts that were functionally deferred on account of their type attributes being non-standard i.e. text/javascript/defer. Doing this causes the parser to ignore them so I want to reload them using JavaScript.
My HTML is as below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>No Title</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript/defer" src="assets/js/test3.js"></script>
<script type="text/javascript/defer" src="assets/js/test4.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script>
$(document).ready(function(){
var defer_js_collection_obj = $("[type='text/javascript/defer']"),
el_head_rq_obj = $('head'),
el_head_obj = el_head_rq_obj[0]
;
if(defer_js_collection_obj.length > 0)
{
//Reload JavaScript
defer_js_collection_obj.each(function() {
var file_src_outer_html_str = this.outerHTML;
var file_src_res_arr = file_src_outer_html_str.match("src *\= *[\"\']{1}(.*?)[\"\']{1}");
var file_src_str = file_src_res_arr[1];
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file_src_str);
document.getElementsByTagName("head")[0].appendChild(fileref);
});
//Unload JavaScript with defer tag
for(var j = defer_js_collection_obj.length-1; j >= 0; j--)
{
defer_js_collection_obj[j].parentNode.removeChild(defer_js_collection_obj[j]);
}
}
});
</script>
</head>
<body>
<div>Load Deferred JavaScript</div>
</body>
</html>
jquery.js is version 1.11.2. test3.js and test4.js reference the javascript files I want to load, and they contain console.log('test3.js is loaded'); and console.log('test4.js is loaded'); respectively.
The issue I'm having is that this script works virtually everywhere else except on Firefox. I'm on a Mac OS X 10.10.5 using Firefox 46.0.1, and I don't see the console.log message when I load the script.
How can I fix this?
It might be a mime type issue. Do you happen to see any message in the console stating "not well-formed"? In any case, this seemed to work for me and I agree that your code did not work in FF when I first tried it.
$(document).ready(function(){
console.log("main");
var $body = $($("body")[0]);
var $scripts = $("[type='text/javascript/defer']");
$scripts.each(function(){
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", $(this).attr("src"));
$body.append(scriptTag);
});
});
Try to append your script at the end of body, so instead do:
document.getElementsByTagName("body")[0].appendChild(fileref);

Categories

Resources