Import JS function in HTML - javascript

I have a JS file that exports some functions. I need one of those in the download attribute of the HTML body tag. How do I import the JavaScript function into the inline HTML?
I tried the following:
JS file
export function initPage() { ... }
HTML file
<script type="module" src="js/script.js"></script>
<body onload="initPage()">
But I get this error message:
Uncaught ReferenceError: initPage is not defined
I've found a Stackoverflow question but lost the URL to it. If someone knows which question I mean, please share the link and I'll delete this question
Thank you!

You could try following:
{...}
<body>
{...}
<!-- End of the body -->
<script type="module">
import {initPage} from '...';
document.addEventListener('DOMContentLoaded', function(event) {
initPage();
});
</script>
</body>
Basically the event listener DOMContentLoaded might be a modern way of solving your problem.

I've found a solution which is very easy, not quite exact that what I wanted but it works:
<script type="module">
import {initPage} from "./js/file.js";
document.querySelector("body").onload = function () { initPage(); } ;
</script>
Now the <script>-Tags with a src attribute aren't necessary anymore.

I did some tries and what seemed to work for me was to remove type="module" from the script tag and the export from the js function
Edit: What I meant was something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/js/script.js"></script>
</head>
<body onload="initPage()">
</body>
</html>
and
function initPage() {
console.log('hupp');
}

Related

How to use JavaScript modules?

I'm looking to do a simple process using the skypack (https://cdn.skypack.dev/) module in javascript.
I have described the following script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sample</title>
</head>
<body>
<button id="button" onclick="mybutton">click</button>
<!-- <script type="module" src="https://cdn.skypack.dev/#...<modulename>...">// <- Uncaught ReferenceError: mybutton is not defined -->
<script type="text/javascript" src="https://cdn.skypack.dev/#...<modulename>...">// <- Uncaught SyntaxError: export declarations may only appear at top level of a module
import { METHOD } from "<modulename>";
function mybutton(){
console.log("aaa");
// ... snip ...
}
</script>
</body>
</html>
However, the module does not work in the script tag.
I have tried two things.
import in the script tag.
This gave me the following error.
Uncaught SyntaxError: export declarations may only appear at top level of a module.
It seems that you need to use <script type="module" when importing a module.
do script type="module" .
This gave the following error:
Uncaught ReferenceError: mybutton is not defined.
It seems that the function defined directly below is not found.
What can I do to resolve these?
I will post the code that worked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="button">click</button>
<script type="module">
document.getElementById('button').addEventListener('click', mybutton);
import { METHOD } from "https://cdn.skypack.dev/.../<modulename>";
function mybutton(){
console.log("aaa");
// METHOD(arg); ...
// ... snip ...
}
</script>
</body>
</html>

JS file not correctly linked to HTML file

At a complete loss here for what I assume is a very simple problem, thanks for the help in advance.
I have a HTML doc;
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Sketch</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="main.js"></script>
<script src="https://use.fontawesome.com/1f87fe0ccc.js"></script>
</head>
and here is my main.js file
function _(selector) {
return document.querySelector(selector);
}
function setup() {
const canvas = createCanvas(650, 600);
canvas.parent("canvas-wrapper");
background = color(255);
}
This should be creating a white canvas on my webpage but nothing is happening and Im concerned I have linked the file incorrectly.
There are several errors with your code. First off, you need to call all the functions that are supposed to run some code: This is how you do it: function_name().
The second thing you do is to define the function createCanvas, This function name looks similar to the P5JS library's createCanvas function, so I'm assuming that you are trying to use P5JS.
Add this to your head tag:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>
For more information please visit P5JS Library

JQuery in Laravel imported but not working

I am playing around with Laravel last version, trying to import and use JS files on the front-end. I have them stored in my folder 'public/js/'.
I have this Blade template you can see below, pizza.blade.php. If you inspect the page source, you can clearly see the JS files are existing, since their links, which are regularly working, are "http://localhost:8000/storage/...".
Nevertheless, they are not working inside the document and, inspecting the network tab, I can see they are not imported.
The image, pizza.png, located in 'public/storage' is displaying correctly.
What am i doing wrong?
Also, is there a better practice to use JS files, such as mix or npm? Thanks in advance.
<!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">
<script>src="{{asset('/js/jquery-3.3.1.js')}}"</script>
<script>src="{{ asset('/js/test.js') }}"</script>
<title>Document</title>
</head>
<body>
<h1 class="ciao">PIZZA LOGO</h1>
<div>
<img src="http://localhost:8000/storage/pizza.png" alt="">
</div>
</body>
<script>
$(document).ready(function () {
$(".ciao").css('display', 'none');
});
</script>
</html>
You have this error
<script>src="{{asset('/js/jquery-3.3.1.js')}}"</script>
this is just script with single javascript variable and string inside. You need this:
<script src="{{asset('/js/jquery-3.3.1.js')}}"></script>
this is html script tag with src attribute.

jQuery: reading variable from external Javascript file

I'm stuck. I really don't know what I'm doing wrong, but I can't get a string returned to a variable in my embedded Javascript.
token.js:
function token () {
return "mysecretstring";
}
HTML Code:
<!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>TXTURE Server Status</title>
<script src="http://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
token_val="";
$.getScript('./token.js', function(data) {
token_val = token();
console.log("function: " + token_val);
});
</script>
</head>
<body>
</body>
</html>
I can do whatever I want, token_val remains empty. Any hints appreciated.
Best regards, Thomas
I do not use that way to reference a function js. I simply load the library js as same your loads jquery-1.12.4.min.js and then I make the call to the function token() from the script.
Code look like that:
<script src="path_to_project/tokens.js" type="text/javascript"></script>
<script type="text/javascript">
token_val = token();
console.log("function: " + token_val);
</script>
Could you try to change your URL argument from "./token.js" to "/token.js"?
I modified the code a little bit to get not confused by too many tokens. Somewhere in the middle I got the error "Unexcpected token error", which is somehow misleading when using a function with the same name. :)
Anyway, that's the code now which works.
Javascript:
function myaccesstoken() {
return "mysecrectstring";
}
HTML:
<script src="token.js" type="text/javascript"></script>
<script type="text/javascript">
let token_val = myaccesstoken();
</script>
Easy as that but somethimes you stare at walls without seeing the windows to your left ... anyway, thanks.
Regards, Thomas
Simply don't use your jQuery $.getScript(), but include the script that contains token() function with
<script type="text/javascript" src="/pathToScript">
And use the function

W3C validator error with Chatango embedded code

So I embedded a chatango tab on my website, but I get this error when validating it for HTML.
The text content of element script was not in the required format: Expected space, tab, newline, or slash but found { instead.
Any workarounds for this? Thank you!
<script id="cid0020000101807397328" data-cfasync="false" async src="//st.chatango.com/js/gz/emb.js" style="width: 603px;height: 471px;">
{"handle":"********","arch":"js","styles":{"a":"000000","b":100,"c":"a0a0a0","d":"FFFFFF","e":"202020","g":"bbbbbb","h":"202020","j":"c0c0c0","k":"0084ef","l":"606060","m":"0084ef","n":"FFFFFF","p":"10","q":"000000","r":100,"pos":"br","cv":1,"cvfntsz":"14px","cvbg":"3366ff","cvw":600,"cvh":30,"surl":0,"allowpm":0,"cnrs":"0.35","ticker":1,"fwtickm":1}}</script>
As Ben said - you cannot use code inside tag with src.
But here is some valid and working solution:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>chatango</title>
</head>
<body>
<script type="text/javascript">
var chatango = document.createElement('script');
chatango.setAttribute('type','text/javascript');
chatango.setAttribute('id','cid0020000101807397328');
chatango.setAttribute('data-cfasync','false');
chatango.setAttribute('async',true);
chatango.setAttribute('src','//st.chatango.com/js/gz/emb.js');
chatango.setAttribute('style','width: 603px;height: 471px;');
chatango.innerHTML = '{"handle":"1shotgg","arch":"js","styles":{"a":"000000","b":100,"c":"a0a0a0","d":"FFFFFF","e":"202020","g":"bbbbbb","h":"202020","j":"c0c0c0","k":"0084ef","l":"606060","m":"0084ef","n":"FFFFFF","p":"10","q":"000000","r":100,"pos":"br","cv":1,"cvfntsz":"14px","cvbg":"3366ff","cvw":600,"cvh":30,"surl":0,"allowpm":0,"cnrs":"0.35","ticker":1,"fwtickm":1}}';
document.body.appendChild(chatango);
</script>
</body>
</html>

Categories

Resources