Javascript executes first then text in body loads later - javascript

Why in my browser when i run this first my java script file runs then it loads the text inside body , but when i ran this in stackoverflow javascript snippet tool it runs fine.
var name= prompt("enter your name");
var age= prompt("enter your age");
var pet_name= prompt("enter your fav pets name");
alert("hi "+name+" your age is "+age+"and you love"+pet_name);
console.log("hi "+name+" your age is "+age+"and you love"+pet_name);
<!DOCTYPE html>
<html>
<head>
<title>testing javascript</title>
</head>
<body>
<h4>Testing of my first java script</h4>
<script type="text/javascript" src="test_1.js"></script>
</body>
</html>

I believe this is because alert, confirm and prompt are all 'blocking' functions and they are being called at the same time the rendering is occuring, try putting the code in a setTimeout or document ready:
document.addEventListener("DOMContentLoaded", function(event) {
// your code
});
or
var delayedScript = function() {
// your code
}
setTimeout(delayedScript, 500);
https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Notes
Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed

It does appear that your code is executing just fine, so the only conclusion I can think of is that the script tag is not correctly implemented.
Verify that it's name is indeed 'test_1.js', and that it is located in the same location as the file your html is located in.
If it is not, you can use a relative path.
A few other points:
The type javascript is redundant as Javascript is the default scripting language of the web.
You are missing spaces after the age variable and after the 'love' string.
I hope this helps :)

The behavior is browser specific. A particular browser may wait until the end of a page's input stream has been reached before rendering the page: perhaps a positioned element located near the end of the file might still need to be rendered at the top of the page.
Now popup dialogs in javascript, like alert, confirm and prompt have a synchronous blocking action on script, which can pause HTML parsing until they have been responded to. So browsers such as Chrome, which don't render until page input has been completed, won't show text from above the script block until the prompts have been answered or dismissed.
Browsers such as Firefox which incrementally render pages may show text from above the script block.
The code snippet facility in SO works differently. It processes content from the HTML box, puts it into the output pane, and then processes content from the script panel. So the HTML content appears first.
Snippet code that requires waiting for a window "load" or document "DOMContentLoaded" event is not tested properly using the snippet facility.
The general solution to using popup dialogs after page rendering is (as suggested already) to defer processing the relevant code until after the "DOMContentLoaded" event has been fired on the document or "load" on the window.

Related

JQuery Ajax not replacing div element with text file

So, I'm quite new to JQuery, and AJAX in general. I've made an app to retrieve data from Spotify's API, which writes to song.txt (This part works just fine. It updates every second, as it should.) and the HTML file will pull the contents of song.txt and change the div with id of 'track'
<!DOCTYPE html>
<html>
<head>
<title>Camashima's Site</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function () {
$(document).ready(function () {
$('#track').load('../output/song.txt');
});
});
</script>
</head>
<body>
Currently Playing:
<div id="track">
.
</div>
</body>
</html>
The JS code posts the html file to the server just fine, and I see Currently playing: but nothing else. So that tells me it's not the issue. So, what am I doing wrong here? It should be loading song.txt into the "track" div, right?
Also, I'm using Goorm-ide to host my container, and the console isn't as in-depth as chrome's dev tools.
Expected: "track" div to be replaced with song.txt contents
Result: Nothing happens.
Whether or not the AJAX part works, the main problem here is that you're (1) adding tons of document.ready events and (2) doing so indefinitely in very rapid succession.
You can correct this by (1) using one document.ready event and setting your interval within that and (2) providing a delay to the interval, even if it's just one second. For example:
$(document).ready(function () {
// execute this code once, and only once, when the document is ready
setInterval(function () {
$('#track').load('../output/song.txt');
}, 1000); // perform this interval operation every 1000 ms
});
From there, you can then begin to reasonably debug the AJAX issue (if there even is one). I realize in a comment on the question you indicated that Chrome developer tools are disabled. So you'll either need to correct that or find another tool to use to debug it. But you're essentially going to want to observe the AJAX requests and responses. Confirm that the address being requested is what you expect it to be, and observe the response from the server. The client-side code here is extremely simple and "works" just fine, but if the overall result isn't what's expected then your only recourse is to debug those interactions with the server.

How to call vbscript function using jQuery?

I'm new to JQuery. I'm trying to call vbscript function inside jQuery. I want to call vbscript on button click using jQuery. I tried calling vbscript function "callfun()" using button onclick() method of javascript for button "Say Hello", and it is working. But when I'm trying to call the same vbscript function "callfun()" using jQuery for button "Say MACRO". It is showing nothing.
(THE BELOW CODE REQUIRES ENABLING OF ACTIVEXOBJECTS.)
Steps to run the below code:
Copy and save the below code in notepad and save the file with .html extension.
Open chrome, search for "IE TAB" extension or download from here, install it, and add it to chrome to enable the plugin icon.
Now open the .html file, click on IE TAB extension.
The link or html page will open automatically directly inside the IE TAB plugin and then the html code can be tested.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/Vbscript">
Function callfun()
Msgbox("Hello!")
End Function
</script>
<script>
$(document).ready(function(){
$("#mac").click(function(){
callfun();
});
});
</script>
</head>
<body>
<input type = "button" onclick = "callfun()" value = "Say Hello" />
<input type = "button" id="mac" value = "Say MACRO" />
</body>
</html>
I even tried making changes in the jQuery script as:
Adding vbscript label before the function.
<script>
$(document).ready(function(){
$("#mac").click(function(){
vbscript:callfun();
});
});
</script>
Adding jQuery attr() function.
<script>
$(document).ready(function(){
$("#mac").attr("onclick", "callfun()");
});
</script>
Adding language in jQuery attr() function.
<script>
$(document).ready(function(){
$("#mac").attr("language", "vbscript").attr("onclick", "callfun");
});
</script>
But nothing called the vbscript function using jQuery.
Someone PLEASE help me or suggest me a way to get it done.
despite the fact you may be using this legitimately its not a 'nice' way to go about doing whatever your trying to do. and most browsers and even windows itself will try its hardest to block what you are doing on multiple levels because security wise this is a very VERY sketchy way of doing whatever your trying to accomplish lol
so the fact this doesnt work does not surprise me. what i would do is to get a packet sniffer running and read all the http data that occours to get clues on if its properly sent out and how server / page responds.
this probably violates the same-orgin policy DOM model of internet rules and stuff or atleast kinda close to violating it, your work is interesting i used to love vbscript but vbscript is becoming rapidly deprecated too
i dont recomend doing this at all: but just for test, you can lower your IE security settings level temporarily. and see if doing that allows sketchy scripts to go through

why the data not loaded in the table when the page in the print dialog

i have a problem here
i make a page that have function for print page that contain of dynamic table. the print function method is open the page html that contain the dynamic table in the new tab then open the print dialog. the process going well but when i add the ajax call for displaying the data in the dynamic table. the data not displayed at the table in the print dialog..but when i cancel the print dialog and the page that must be printed show off the data is displaying there...
how to fix it.
this the picture of the page
i use this code for print that
<script>
function myFunction() {
window.open('SPL.html','','height=650,width=1200').print();
}
</script>
You didnt provided yet the code of your generator, so I simply explain you why its not working and what you can do.
A good reference for window Mozilla Window Open
You can read there more details about possible functions and more. Your problem is, with:
window.open('SPL.html','','height=650,width=1200').print();
Directly after opening the file you call the print function, at this moment your script and ajax request don´t have finished yet. Thats why it just shows you the current state with the predefined html and css code.
So what you have to do is simply call print after it has finished. There are tons of ways to achieve this.
The simplest way would it to open it like this:
window.open('SPL.html','','height=650,width=1200')
Inside your SPL.html you stack your js script inside:
$(document).ready() {
//Your Generator
}
This little piece keeps safe that all dependencys (external scripts and dom elements) are created before your generator runs and it gives us the possibility for the next function:
$(window).load(function(){
window.print()
});
This one is a version of the globalEventHandler window.onload. It basicly ,if you read the documentation, fires after everything is loaded, including images, frames, objects and so on. And the tricky part also after document.ready, this makes it sure that our generator is finished before we run the print command.
I hope this helps, If you really want to stick the print command inside your first page I can give you an example of this too. But it is not as bullet prove as this solution. Ah and if you want to stick with #Saurabh solution you have to use allow-modals for your Iframe, if not it wouldn´t be possible to print. Is also mentioned in the official documentation.
This issue is caused because the page is not completely loaded before calling the print function.
Update: Using jQuery
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function(){
$('#loaderFrame').load(function(){
var w = (this.contentWindow || this.contentDocument.defaultView);
w.print();
});
$('#loaderFrame').attr('src', 'SPL.html');
});
});
</script>
<style>
#loaderFrame{
visibility: hidden;
height: 1px;
width: 1px;
}
</style>
</head>
<body>
<iframe id="loaderFrame" ></iframe>
</body>
</html>

Change html before rendering to avoid a flicker

I have code I'd like to run before the page is rendered. For example updating dates from absolute time to relative time or converting raw text (or markdown) to html. If I reload the page several times I can see occasionally there's flickering updating the changes. How do I run the code as it's drawn instead at the end where it needs to redraw everything?
I tried document.addEventListener('beforeload' it appears that event is depreciated and no longer supported in chrome
You'll need to think about your page lifecycle.
When your page is being loaded, if a <script> tag is encountered, it will immediately be executed, and prevent any more content being rendered until that script is complete. This isn't recommended practice.
But, to answer your question, you could do something like this:
<p>Your next reward will be available in <span id="nextRewardTime">3600</span>.</p>
<script type="text/javascript">
var $el = $('#nextRewardTime');
$el.text(format($el.text());
</script>
<p>Come back soon!</p>
Now, immediately after the first <p> is downloaded by the browser, it'll hit the <script> tag and execute the JS. Only once that is complete will it download the next <p> tag ('Come back soon!').
You can't attach an event handler to the Javascript before it's been rendered on the DOM, because... well... it's not on the DOM.
The better way of doing this is to format the thing correctly on the server in the first place.
Edit: Also, scattering script tags throughout your page makes your code really unmaintainable!
I would use document.readyState and a self-invoking function:
<body>
<script>
function executeFunction() {
//do stuff - such as check for anchor tags
$("a").html('Replaced');
if (document.readyState === 'loading') executeFunction(); // repeat to ensure all the tags get innerHTML-ed
}
(function(){
if (document.readyState === 'loading') executeFunction();
})();
</script>
<!-- more HTML -->
</body>
It seems that you want JS to execute as the page is loading. You may also want to try using uninitialized as the ready state (which occurs before "loading").

Run JavaScript in PDF When Document Opens

Using Adobe Acrobat Pro DC, I need certain form fields to clear their values when the document opens. Here's one line I've placed in Tools > JavaScript > Document JavaScripts:
getField("Patient").value = "";
However, that doesn't run when the PDF is opened. (It works when called from a Document Action.)
Thanks
The exact moment when a document-level script is executed is not known, and that means that a field may not yet have been created when the script runs.
In my experience, when it comes to set field values when the document opens, it is much safer to use the pageOpen event of the page at which the document opens.
Note: when you have a multi-page document, you will need to make sure that this piece of code gets executed only once; this is done in a way like this:
In a document-level script define:
var loaded = 0 ;
In the pageOpen script have this construct:
if (loaded < 1) {
// execute code when document opens
loaded++ ;
} else {
// execute code when returning to the page
}
And that takes care of the situation.

Categories

Resources