Javascript - Dynamically load a fragment of HTML and run script - javascript

I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?

Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol

Related

bootstrap script has not finished loading before the tooltip initialization

I have a simple one page website with bootstrap 5 set up using spring boot with thymeleaf.
On this page I want e.g. to use the bootstrap tooltip. The problem is that the function to initialize the tooltip fires before the bootstrap script has finished loading so there will be an error and the page will not load correctly.
<head>
... // css and meta omitted for brevity
<script th:src="#{/js/bootstrap.bundle.min.js}" async="true"></script>
</head>
<body>
... // page content
<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>
</body>
I tried to place the bootstrap script
in the head section
with async attribute
with defer attribute
a combination of the attributes
in the body section directly before the tooltip init script
but nothing prevents the second script to fire before the first script has finished loading.
I have read the HTML spec here but in the end I'm not sure if the loading of the script is truly the problem.
Has someone an idea to definitly prevent this error?
Finally solved this problem.
I put all the javascript code in a seperate js-file.
Then I load this file after the bootstrap file at the end of the body and everything works fine.
<head>
... //css and meta
</head>
<body>
... // page content
<script th:src="#{/js/bootstrap.bundle.min.js}"></script>
<script th:src="#{/js/myfunction.js}"></script>
</body>

How to design javascript

I have java script file that reads in a csv file, and has many functions to to visualize the data differently, using d3. I want each visualization to be displayed in different html pages. Ive made every html page, refer to the javascript file. Each page also has its own script that calls functions from the referred javascript file.
The problem, I am facing is that when ever I go to a new page, the function gets called before the data being read. Only works when refreshing the page. I there a way to just read the data in once, and every page can access it.
If you look at the code below, callingFunction() returns undefined (maybe because data is not stored in var data?) The callingFunction() works fine when the page is refreshed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>D3</title>
**<script src="my.js"></script>** //my script file
</head>
<body>
<script>
callFunction(); //uses var data defined in my.js
</script>
Here is the "my.js":
var data;
function data(file){d3.csv("file", function (error, data) {
ds = data;
callFunction();
}
load your script after the target DOM :
<canvas></canvas>
...........................
<script type="text/javascript"></script>
Use angularJs Js library: it organize your js code according to MVC design pattern.
If you have more than one method to implement a business logic , Use console.time & console.timeEnd to evaluate code performance .
console.time('anID');
// Here your code
console.timeEnd('anID');

Javascript can't find the script tag's id

I am facing problem with javascript document.getElementByID function. The HTML file is:
...
<script
id="scriptID"
type="text/javascript"
src="http://external.script.com/file.js">
</script>
...
When the page is loaded, the script is successfully included, but when executing expression from that file (the script is executed automaticaly after loading it):
... = document.getElementById('scriptID').src
The script fails with message saying that "document.getElementById('scriptID') is null".
Can anybody tell me, why it is null if the tag is the script tag itself?
Thx for any response.
EDIT:
I don't know if that is relevant, but the page is built in a bit more complicated way.
There is page of some product. When the customer orders that product, there is a div loaded by AJAX with some "Thanks for order" and that contains the script. Then the script is executed.
May be your DOM is not ready when you are try to get src of script,
<script id="scriptID" type="text/javascript" src="http://external.script.com/file.js">
</script>
window.onload=function()
{
alert( document.getElementById('scriptID').src);
}
Its workinfg fine SEE

How to call external JavaScript function in HTML

I have a small chunk of code I can't seem to get working. I am building a website and using JavaScript for the first time. I have my JavaScript code in an external file 'Marq_Msg.js' which looks like this:
var Messages = new Array();
Messages[0] = "This is message 1";
Messages[1] = "This is message 2";
Messages[2] = "This is message 3";
Messages[3] = "This is message 4";
function scroll_messages()
{
for (var i = 0; i < Messages.length; i++)
document.write(Message[i]);
}
and in my HTML file 'Index.html' I am trying to call it like this:
<div id="logo">
<marquee scrollamount="5" direction="left" loop="true" height="100%" width="100%">
<strong><font color="white"><script src="Marq_Msg.js">scroll_messages()</script></font></strong>
</marquee>
</div>
The 'logo' div is a CSS piece that I'm trying to marquee inside of. If I put the code embedded inside the 'head' tag and call it, it works perfectly! There are a few other things id like to do with this code (like space the messages out a little) but I can't get the code to work in the first place. I've also tried adding:
<script src="Marq_Msg.js"></script>
in the 'head' tag with a separate call, that was a no go. I also tried instead using:
<script type="text/javascript" src="Marq_Msg.js">scroll_messages()</script>
Hell, i even had the function try returning a string (even hardcoded a simple "hello" to be returned) but that didnt work either with and without the 'type':
//Marq_Msg.js
function scroll_messages()
{
return "hello";
}
//index.html
<script type="text/javascript" src="Marq_Msg.js">document.write(scroll_messages())</script>
What am I missing? Any help would be greatly appreciated!! I've looked all over Google, and every site I find wants to do it using some 'form'. I just want messages to be displayed across, no form attached.
If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
a <script> to load the external script
a <script> to hold your inline code (with the call to the function in the external script)
scroll_messages();
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page.
Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
Result :
If anyone still has the reference error is probably because you are loading your Javascript with defer, or it's in the bottom of the body so when the function gets called your function still doesn't exist.

How to access javascript variables in dynamically-loaded html page?

I've got a html page which loads another html page into one of its divs via Ajax. Something like:
Base html page:
<html>
<head>
<script type='text/javascript'>
var greeting = "Hello";
</script>
</head>
<body>
<div id="details-main-content">
</div>
</body>
</html>
Page that gets loaded into the one above (uses django templating so whatever is placed in the 'head' block ends up in the 'head' tag of the base page):
{% block head %}
<script type="text/javascript" language="javascript">
alert("Greeting: " + greeting);
</script>
{% endblock %}
<div>
Hello, world!
</div>
The child content gets loaded when a button is clicked, via a Javascript function (using JQuery) such as this:
function loadContent(url) {
// Load external content via AJAX.
$( '.details-main-content' ).load( "/foo.html", function(){
});
}
The page loads correctly, the child content displays exactly desired, inside the templatepage.
Is it possible to access the JS variables in the base page from the inner page (since the inner page is nestled inside of the outer page)?
Any help is greatly appreciated.
Thanks
EDIT:
I think the issue I was having was due to having the following line in the of the base html page:
var gender = null;
var age = null;
Which, each time a new page would be loaded through the load() function, would re-init the variables back to null. Oops
Yes. It's just a single page, before and after the load (which uses XMLHttpRequest). As a simple example, if you had:
var message = "Annoying message";
you could have
Message
in the inner page.
EDIT: If you're having issues, it might be due to the issue noted on the jQuery load documentation:
During this process, browsers often
filter elements from the document such
as <html>, <title>, or <head>
elements. As a result, the elements
retrieved by .load() may not be
exactly the same as if the document
were retrieved directly by the
browser.
There is no "inner" and "outer" page in your example. You just work with single page, some content of which is loaded dynamically, but it is not treated any differently by the browser.

Categories

Resources