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.
Related
I have a html file and 2 JavaScript files: mainscript.js and script1.js. I inject the script1.js inside the mainscript.js. However, what happens is that by calling script1.js, the htmltags created by mainscript.js got removed. Any idea why this happens?
html code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Linear Call</title>
</head>
<body>
<div id="main"><p>hi</p></div>
<script src="js/recursion_linear/MainScript.js">
</script>
</body>
</html>
mainscript.js:
const loadScript = async(url) => {
const response = await fetch(url)
const script = await response.text()
eval(script)
}
var s = document.createElement("span");
document.write("<br>");
s.innerText="This is main script";
s.id="mainscript";
document.body.append(s);
const scriptUrl_1 = "js/recursion_linear/Script1.js"
loadScript(scriptUrl_1)
script1.js:
document.write("<br>");
var s = document.createElement("span");
s.innerText="This is Script1";
s.id="script1";
document.body.append(s);
The output is
This is Script1
While the expected one is
This is main script
This is Script1
I want to change its script in the head section of the HTML dynamically on clicking the button and want to reload the page with a new script(with its new values) replacing previous one with JavaScript.
/* To change the root api */
function passRoot(data) {
const parsedData = JSON.parse(data);
var newScript = document.createElement("script");
newScript.id = "someID";
newScript.setAttribute("data-root", parsedData["data-root"]);
newScript.setAttribute("api-root", parsedData["api-root"]);
newScript.setAttribute("src", parsedData["src"]);
document.head.appendChild(newScript);
window.location.reload();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script id="someID" api-root="some-api-value" data-root="some-data-value" src="some-src-value"></script>
</head>
<body>
script change:
<textarea style="font-size: 9px; width: 90%; height: 30%" id="passroot">
{"api-root": "enter new value", "data-root": "enter new value", "src":"some-new-src-value"}</textarea
>
<div>
<button onclick="passRoot(document.querySelector('#passroot').value)">
Submit to change script
</button>
</div>
**************html-starts***********************************<br>
stuff I manage with bundle, here I want to load new bundle after providing new url in the src of script tag
</body>
</html>
Please open view frame source in the code snippet to see the script tag.
Please help!
Why you want to change the script tag. If you want to load your js on some event. Let's say button click. Please go for Dynamic import that will run your script file.
When you reload the page the script will be removed. So you need to use localStorage to keep current script attribute:
let scriptData = localStorage.getItem('script');
if (scriptData)
craeteScript(scriptData);
function craeteScript(data) {
localStorage.setItem('script', data)
const parsedData = JSON.parse(data);
var newScript = document.createElement("script");
newScript.id = "someID";
newScript.setAttribute("data-root", parsedData["data-root"]);
newScript.setAttribute("api-root", parsedData["api-root"]);
newScript.setAttribute("src", parsedData["src"]);
document.body.appendChild(newScript);
}
function passRoot(data) {
craeteScript(data);
window.location.reload();
}
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);
I want to make the method or only copy to clipboard the "syntax" part of a paragraph.
I've done the logic to get the specific part of content I want and stored it in variable "syntaxClean". Now I just need to copy it somehow.
document.execCommand("copy"); would be awesome, but I just can't seem to make it 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>
<pre id="test"></pre>
<script>
const message = "====== Executor details =======\nathena#21.109.21.25 (tunneled:39516)\n====== Request details ========\nClass....................: com.ericsson.athena.taf.os.linux.commands.common.SimpleCmdRequest\nThread : ................: main\nExpected prompt..........: ^((?![<?]|\\\\.{3}|(\\\\S+\\\\s){6,}).)*[>#$%]+(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*\\\\s(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*$|#\\\\s\\\\u001B\\\\[6n\nPrompt forced............: false\nTimeout..................: 20000ms\nSyntax...................: lsb_release -i\n"
document.getElementById("test").append(message);
var res = message.split("\n");
for (var i in res) {
if (res[i].indexOf("Syntax") != -1) {
var syntax = res[i].split(':');
var syntaxClean = syntax[1].slice(1);
console.log(syntaxClean);
}
}
</script>
</body>
</html>
In this example I would like to copy to clipboard "lsb_release -i" and I have it stored in variable syntaxClean as I've already said above.
Any help is appreciated!
You can achieve this by creating a dummy textarea like this:
<!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>
<pre id="test"></pre>
<button onclick="copy()">Copy</button>
<script>
const message = "====== Executor details =======\nathena#21.109.21.25 (tunneled:39516)\n====== Request details ========\nClass....................: com.ericsson.athena.taf.os.linux.commands.common.SimpleCmdRequest\nThread : ................: main\nExpected prompt..........: ^((?![<?]|\\\\.{3}|(\\\\S+\\\\s){6,}).)*[>#$%]+(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*\\\\s(\\\\\\\\u001B\\\\[(\\\\d;?)*[m|n|K])*$|#\\\\s\\\\u001B\\\\[6n\nPrompt forced............: false\nTimeout..................: 20000ms\nSyntax...................: lsb_release -i\n"
document.getElementById("test").append(message);
function copy() {
var res = message.split("\n");
for (var i in res) {
if (res[i].indexOf("Syntax") != -1) {
var syntax = res[i].split(':');
var syntaxClean = syntax[1].slice(1);
console.log(syntaxClean);
copyToClipboard(syntaxClean);
}
}
}
function copyToClipboard(text) {
var dummyElm = document.createElement("textarea");
document.body.appendChild(dummyElm);
dummyElm.value = text;
dummyElm.select();
document.execCommand("copy");
document.body.removeChild(dummyElm);
}
</script>
</body>
</html>
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);