I'm trying to add \node_modules\sip.js\dist\sip.min.js , to my html file. I tried to import like import * as SIP from 'sip.js/dist/sip'; in my component.ts but this work only if I call some function from it. But I need my html file to read this sip.min.js.
Also I tried to download local this files and added in my html file
<script src="js/sip-0.5.0.js"></script>
<script src="js/ua.js"></script>
and added:
public loadScript() {
console.log("preparing to load...");
let node = document.createElement('script');
node.src = this.url;
node.type = "text/javascript";
node.async = true;
node.charset = "utf-8";
document.getElementsByTagName("head")[0].appendChild(node);
}
ngOnInit() {
this.loadAPI = new Promise(resolve => {
console.log("resolving promise...");
this.loadScript();
});
}
But this is not working
You could add them to body. Also your paths should be available from client side. But adding scripts in Init event is bad practice - it is added each time as component is created. I have added scripts in service - it executes once.
const files = ['js/sip-0.5.0.js','js/ua.js']
files.forEach((file) => {
const fileRef = document.createElement('script');
fileRef.setAttribute('type', 'text/javascript');
fileRef.setAttribute('src', file);
fileRef.onload = function () {
console.log('loaded' + file);
};
document.body.appendChild(fileRef);
});
But this approach is good only for dynamic adding scripts based on some condition. If your scripts are independent from other files you could just add it to bundle file without any manually struggling.
Related
I have an asp.net application, where I need to add a script in the section of my html, and a value in that script needs to change based on the environment (TEST, QA etc..). For simplicity lets just say this is my script, where DisplayValue is the value that needs to be dynamic:
<head>
<script>
alert("Hello World! Value='" + DisplayValue + "'");
</script>
</head>
This is an asp.net application, but there is no corresponding .aspx file, just plain old html. Is it possible to read the value from the web.config? Some other way I haven't thought of?
My solution was to create a separate script file for each environment. Then, based off the url of the page, determine which environment I am running in and dynamically load the correct script.
<script>
function loadJS(url, async = true) {
let scriptElement = document.createElement("script");
scriptElement.setAttribute("src", url);
scriptElement.setAttribute("type", "text/javascript");
scriptElement.setAttribute("async", async);
document.head.appendChild(scriptElement);
//success
scriptElement.addEventListener("load", () => {
console.log("Script file loaded.")
});
//error
scriptElement.addEventListener("error", (ev) => {
console.log("Error loading script file", ev);
});
}
var url = window.location.href.toUpperCase();
if (url.indexOf("WWWQA.") >= 0) {
//Load script for QA environment
loadJS("Scripts/QA-SCRIPT.js", true);
}
else if (url.indexOf("WWW.") >= 0) {
//Load script for PROD environment
loadJS("Scripts/PROD-SCRIPT.js", true);
}
</script>
So I have my main.php page on which you have a button:
<button onclick="Raport()" type="button">Raport</button>
It calls a JavaScript function:
<script>
function Raport() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("Raport").innerHTML = this.responseText;
}
xhttp.open("GET", "Raport.php");
xhttp.send();
</script>
raport.php called by javascript run powershell script:
<?php Shell_Exec('powershell -InputFormat none -ExecutionPolicy ByPass -NoProfile -Command "& { . \"..\Scripts\export.ps1\"; }"'); ?>
Which create csv file on server.
Now my goal is to download that file when Raport() function end. I was able to allow user to download that file by:
fetch("http://host/scripts/raport.csv")
.then((res) => { return res.blob(); })
.then((data) => {
var a = document.createElement("a");
a.href = window.URL.createObjectURL(data);
a.download = "Raport.csv";
a.click();
But it will not wait until Raport() function end. Then I tried adding after xhttp.send():
.done(Raport() {
(fetch from above)
})
.fail(Raport() {
// Tell the user something bad happened
});
But it end up not working.
Any advice how should I aproach this problem and if my approach is correct one.
I found interesting code on stack overflow, but the only thing I don't like about it is that it uses JQuery that is imported via the Internet, and I need it all to work without connecting to the Internet. Can you please tell me how this can be changed?
Code:
void handleRoot() {
snprintf ( htmlResponse, 3000,
"<!DOCTYPE html>\
<html lang=\"en\">\
<head>\
<meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
</head>\
<body>\
<h1>Time</h1>\
<input type='text' name='date_hh' id='date_hh' size=2 autofocus> hh \
<div>\
<br><button id=\"save_button\">Save</button>\
</div>\
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\
<script>\
var hh;\
$('#save_button').click(function(e){\
e.preventDefault();\
hh = $('#date_hh').val();\
$.get('/save?hh=' + hh , function(data){\
console.log(data);\
});\
});\
</script>\
</body>\
</html>");
server.send ( 200, "text/html", htmlResponse );
}
void handleSave() {
if (server.arg("hh")!= ""){
Serial.println("Hours: " + server.arg("hh"));
}
}
void setup() {
// Start serial
Serial.begin(115200);
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
server.on ( "/", handleRoot );
server.on ("/save", handleSave);
server.begin();
}
void loop() {
server.handleClient();
}
The minified jquery javascript can be stored on the ESP and served up by the module when the browser requests it.
One easy way to do this is to use the SPI Flash File System to serve up the HTML as well as the JQuery javascript.
This means creating an index.html in a data sub-directory in the sketch. Add the HTML in the original sketch into the file. Also change the script source in this file to a relative path:
<script src="jquery.min.js"></script>
Then download jquery.min.js and copy this into the data sub-directory as well.
The example code at https://tttapa.github.io/ESP8266/Chap11%20-%20SPIFFS.html can be used as a starting point for the rest of the code. The main parts of this involve initializing SPIFFS and setting up the handler for the file request:
SPIFFS.begin();
server.onNotFound([]() {
if (!handleFileRead(server.uri()))
server.send(404, "text/plain", "404: Not Found");
});
// retain the save endpoint
server.on("/save", handleSave);
server.begin();
Then implement the file handler and its content type handler:
String getContentType(String filename)
{
if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".ico")) return "image/x-icon";
return "text/plain";
}
bool handleFileRead(String path) {
Serial.println("handleFileRead: " + path);
if (path.endsWith("/"))
{
path += "index.html";
}
String contentType = getContentType(path);
if (SPIFFS.exists(path))
{
File file = SPIFFS.open(path, "r");
size_t sent = server.streamFile(file, contentType);
file.close();
return true;
}
Serial.println("\tFile Not Found");
return false;
}
Alternate Approach: Remove the JQuery dependency
An alternative approach is to rewrite the javascript so that JQuery is not required.
This involves registering an onclick handler on the button (https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers), getting the value from the input field (https://stackoverflow.com/a/11563667/1373856) and sending a GET request (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send)
You just has to include it as script-tag with the local path on your machine.
<script src="path-to-jquery/jquery.min.js" type="text/javascript"></script>
Edit: First you have to download the needed jquery file and store it in your local path. The needed path-to-jquery should than be a relative path from the html-file to the jquery.
so I've downloaded a few blank HTML files with no file extensions.
(I know these are HTML because if I manually add .HTML to the end and open the file, / the file contains html elements.... like etc.)
So they're located in my downloads folder. I'm simply trying to add a file extension to each of these files in the dir folder "download".
Here's my code:
var fs = require('fs');
var files = fs.readdirSync('C:/Users/Nikki/Downloads').forEach(file => {
console.log(file);
//There is a file named "desktop.ini", skip this file.
if (file === "desktop.ini") {
console.log("desktop file")
} else {
//not sure why it doesn't change the file extension. Maybe because there is none!?
var replaceExt = require('replace-ext');
var path = 'C:/Users/Nikki/Downloads/' + file;
var newPath = replaceExt(path, '.html');
console.log(newPath);
}
/*
fs.rename(file, file+'.html', () => {
console.log("\nFile Renamed!\n");
// doesnt work... either...
});
*/
});
How can I add the HTML file extension to each of these files?
If your file doesn't have a file extension, you can try the following code snippet :
var pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".html";
I am trying to load file files asynchronously with javascript, here is the code:
var jsFiles = [ 'js/enscroll.min.js',
'js/jp_custom.js',
'js/jquery.uploadifive.js',
'js/raphael-min.js',
'js/pgloader.js',
'js/jquery.custom.js' ];
for( var i=0, j=jsFiles.length; i < j; i++ ){
var file = jsFiles.shift();
asyncLoader(file, i);
}
function asyncLoader( filename, position, fileType ){
var type = typeof fileType == "undefined" ? "script" : fileType,
resource = document.createElement(type),
script = document.getElementsByTagName(type)[position+1];
resource.src = filename;
resource.type = "text/javascript";
script.parentNode.insertBefore(resource, script);
}
i am useing this code under the <head></head> tag means in the top of the file, and here is how do used the files related functionalities:
$(function(){
$(window).load(function(){
// Start to use the related files
});
})
at the bottom of the page so that after load the window my files working properly, i just want to know is this the best way to reduce the page load time(only javascript)? or what i have to with it to make it more efficient?