How to use HTML file variables in external JS file - javascript

I have an html file where I import a JS module from chessboard.js
<html lang="en">
<head>
<link rel="stylesheet" href="./chessboardFiles/css/chessboard-1.0.0.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script id="import" src="./chessboardFiles/js/chessboard-1.0.0.js"></script>
<title></title>
</head>
<body>
<div id="board1" style="width: 400px"></div>
<script>
var board2 = Chessboard("board1", "start");
</script>
</body>
</html>
The only problem is that I want to write what's in the body's <script> tag in a separate JS file then add it to this html document via <script src='...'> however the <script id="import" ...> file that is imported is not exactly a module so I cant just do import * as C from chessboard-1.0.0.js in a new JS file because I get a
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. error in the console.
So is there any way to get the variables available in the HTML document (i.e Chessboard()) available in an external JS file? How could I do this?

You could write to global window variables, or have everything in the window scope. Ex: window.board = Chessboard(...), and you can access that from different files if the script is run later than the definition.

Related

How to use javascript module on an HTML page in a second inline script

I have a JavaScript module mymmodule.js exporting a list:
export var mylist = ['Hallo', 'duda'];
Normally this module is used in other modules and this works fine. But additionally I want to use the export(s) of the module as-is in an inline script on an HTML page. I tried to copy the exports to the window object:
<html>
<head>
<script type="module">import * as mm from './mymodule.js'; window.mm = mm;</script>
</head>
<h1>MyMain</h1>
<p>
<div id = "info">...</div>
</p>
<script type="text/javascript">
document.getElementById('info').textContent = window.mm.mylist;
</script>
</html>
but I get the error "window.mm is undefined" in the console. I tried referencing mm.mylist instead of window.mm.mylist with no better result.
How can I reference the exports of a module in a second inline script on the HTML page?
The problem is that modules are execute at the same stage as pscripts with the defer attribute](https://javascript.info/script-async-defer#defer), i.e. after reading the page and executing JavaScript in script tags.
Therefore, when the browser sees
document.getElementById('info').textContent = mm.mylist
the mymodule.js script hasn't been executed and the mm object is not available yet.
To mitigate this you need to run code referencing exports from mymodule after the DOM is completely loaded, e.g. in the onload event:
<html>
<head>
<script type="module">import * as mm from './mymodule.js'; window.mm = mm;</script>
</head>
<h1>MyMain</h1>
<p>
<div id = "info">...</div>
</p>
<script type="text/javascript">
window.onload = function() {
document.getElementById('info').textContent = mm.mylist;
}
</script>
</html>

onClick to call function from another JS file with react

I have the following html code in my render react component:
<button id="execute-request-button">Authorize</button>
And I am trying to call this function from my external JS file
$("#execute-request-button").click(function() {
console.log("CLICK");
handleAuthClick(event);
});
I am calling the external JS file in my HTML as well. It doesn't print to the console when I click my authorize button. Also I console logged at the very first of the external JS file to see if it's loaded and its not. I know the file path is right since I am not getting any errors.
Any thoughts?
EDIT
I moved my script tag to the top of my html file .
<script src="../src/YoutubeAPI/upload.js"></script> and I get the following error Refused to execute script from 'http://localhost:3000/src/YoutubeAPI/upload.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="../src/YoutubeAPI/upload.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<title>STEMuli</title>
</head>
<body>
<noscript>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T"
crossorigin="anonymous"></script>
</noscript>
<div id="root"></div>
</body>
</html>
I think you add event click before your code render html.
You can try:
<button id="execute-request-button" onclick="yourEvent()">Authorize</button>
and define yourEvent is method of your component.
Add your event listener when the document is ready:
$(document).ready(()=> {
$("#execute-request-button").click(function() {
alert()
});
})
Example: https://jsfiddle.net/n5u2wwjg/90476/
I see nothing wrong with the code. Remember to place the reference to jQuery before your own Javascript file. If you place it after, the methods in your own Javascript file will be undefined as it is calling jQuery.
$("#execute-request-button").click(function() {
console.log("CLICK");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="execute-request-button">Authorize</button>

HTML is not reading external Javascript file

I am trying to write a very simple HTML page that displays a message generated by a JS file. I am somewhat new to HTML / JS and I am certain there is something pretty simple I am missing, but I cannot for the life of me get the page to read the script. When I load the page, it is completely BLANK without any errors in the inspector.
This is the project folder structure:
-Project (folder)
--templates (folder)
----home.html
--src (folder)
----home.js
--styles (folder)
----home.css
Also, I'm pretty sure that my HTML page SEES the script, because when I remove or rename the script, I get an error in the browser's inspector telling me that it cannot find the script. So it SEES the script, it just is not running it for some reason.
Here is the code...
home.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="../styles/home.css"></link>
<script type="type/javascript" src="../src/home.js"></script>
</head>
<body>
<div id="bodytext"></div>
</body>
</html>
home.js:
(function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
})();
Could some generous soul out there please clue me in to what extremely simple mistake I'm making?
Thank You!
Value for type attribute should be text/javascript as follows:
<script type="text/javascript" src="../src/home.js"></script>
Your script is running before the DOM is completely done loading. If you put your <script> tag right before your closing body tag (</body>), it will run after the DOM is loaded, and you will be able to traverse the DOM like normal.
Value for type attribute should be text/javascript as follows
enter code here
ALong with this you will have to change your java script code as follows, so that script gets executed only when page is completely loaded & document object is availabe.
window.onload = function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
};
What worked for me was adding charset="utf-8" to my css link as well as my javascript script (for me, both did not work). Example:
<link rel="stylesheet" type="text/css" href="css/main.css" charset="utf-8"></link>
<script src="javascript/script.js" charset="utf-8"></script>

External file script is not loading

Iam using load() for loading external html file.
$("#header_section").load("header.html");
$("#sidemenu_section").load("side_menu.html");
Here, HTML file is loaded and css also loaded but script file is not loading in the page
<script src="js/utility.js"></script>
I tried to declare the above script file inside the head and inside the body. Both are not working.
Check your relative path to the utility.js file and make sure to load juery.js library before load utility.js file.
and finally try this,
<script type="text/javascript" src="${pageContext.request.contextPath}/js/utility.js"></script>
to load the utility.js file.
I think you forget to add jquery.min.js file. use below code.
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/utility.js"></script>
</head>
jQuery may only execute your code with the type attribute set to "text/javascript", per this bug filed a long time ago:
http://bugs.jquery.com/ticket/3733
Try this ...
<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>
The jQuery code that adds HTML to the DOM always strips out <script> tags. It runs them and then throws them away.
An exception to that behavior is when you use "$.load()" with the hack that allows you to load a fragment of a page:
$.load("http://something.com/whatever #stuff_I_want", function() { ... });
In that case, the scripts are stripped and not evaluated/run.

How to create Backbone View in a separate js file

I'm trying to understand how to modularize the Backbone ToDo tutorial
Originally everything is inside the same file, but if I try to extract to another file:
var TodoView = Backbone.View.extend({
...
});
then this throws an error:
var view = new TodoView({model: todo});
**Uncaught TypeError: undefined is not a function**
It's probably due to a scope issue, but I don't know how to create a reference inside the $(function() so I can create this new object inside the main function.
Assuming that your first code part is TodoView.js,
and your second code part is app.js.
Write your html file like this,
<html>
<head>
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
// your dom
</body>
</html>
(Edited, at 2015-07-27)
sorry for my late reply.
how about this?
<html>
<head></head>
<body>
<!-- your dom -->
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
In many case, most javascript codes are appended to just before </body>, so that javascript can use your dom!
You can use something like require.js to load your external files and manage dependancies.
Ok, the solution was to move the script references to the end of the body instead of inside the head tags.
I think that the reason is that TodoView.js is making use of templates that were defined in the body, and since the js file was being loaded before the body, the templates were not yet available.

Categories

Resources