How to run some code before page is displayed [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have trouble running some code before page loads in jquery or js. Anything I do the page would have a brief load then my codes run. I run code before user sees the page but it loads in a brief milliseconds then my code runs.
I have done some solutions and didn't do what I want:
I've put my codes before document.ready
I've put my code in head section
I've put my code in a function then called the function in head tag
I also tried onload() in js
But the same result: my code runs after milliseconds and user sees the page before running code in these milliseconds
Any ideas?

Start with body hidden and show it after your code is executed.
<html>
...
<body style='display:none'>
...
<script>
$(document).ready( function() {
...
$(document.body).show();
})
</script>
</body>
</html>

Scripts inside the <head> will run before this occurs, but there won't be access to the elements on the page.
Try this code
<body>
<script type="text/javascript">
alert("After click ok you'll see the page content!!!");
</script>
rest of the page
</body>

You could put your code in 'loading' state of document via document.readyState but in this state DOM is not ready to operate. Here your have example how to use document.readyState https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState#Different_states_of_readiness What actualy do you want to do?

You shouldn't but anycode in <head>
My suggestion is to use loader, so make the body tag invisible using css display:none
so your code will be run as if the page isn't loaded yet.
then you add $(document).ready({$('body').css('display','block')})

Jquery and Javascript are client side languages, and are read by the browser as the page loads.
Usually we would use something like:
$(document).ready(function(){
//do stuff
});
This is to make sure the elements are loaded on screen before the JS functions run to make sure any elements that are needed for the script have been loaded.
What you seem to be doing is running the script at the same time as the page loads so there might be something in the script that prevents the rest of the HTML from loading as this is running and thats why you see the load time.
You should look at PHP. (hypertext pre-processor) This is a server side language rather than client side. So it pre-processes what you want server side and then sends that to the users client/browser.
Check out http://www.developphp.com/

Related

document.write inside script does not perform the script

According to the instructions that I am following these codes below should be able to embed a button that would perform a certain function.
<script>
document.write('<scriptsrc="sourcefile/filename.js">/script>')
</script>
The problem is that the above code displays /script> instead of displaying the button that the js file should display once run. Now when I try to edit it this way
<script>
document.write('<scriptsrc="sourcefile/filename.js"></script>')
</script>
') is displayed which clearly means that the first </script> closes the first <script> tag which should close the second one instead.
sorry cause I find it hard to explain it further.
Looks like you just want to include a javascript file into the current html page.
As described in http://javascript.info/tutorial/document-write
That's convenient, but a bad way, because loading a script may block the rest of page from rendering.
Using DOM is a preferred way, other than the example posted on that page, below is how twitter does it.
<script>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;js.src=p+"://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","twitter-wjs");
</script>

addEventListener load on ajax load WITHOUT jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have 4 html files and 4 javascript files. Each javascript file is loaded externally from each html file
index.html loads javascript.js
1.html loads javascript1.js
2.html loads javascript2.js
3.html loads javascript3.js
The issue that I'm having is that index.html uses AJAX to load one of the 3 other pages when a specific button is pressed. Then what is supposed to happen is that particular page would load its own corresponding javascript program which at the end of that program contains a window.addEventListener that should run on "load" and run the function "registerListeners". RegisterListeners then registers an event listener on a button on that page which currentyl just displays an alert for testing.
What I have figured out is that the parameter "load" for window.addEventLisener doesnt seem to be valid when the page is loaded dynamically with ajax.
I cant put all of the code in the main javascript because it contains some getElementById calls that call elements from one of the numbered pages that, if executed on main page load will generate errors because those specific ID's dont exist yet.
This is homework and so I need to get pointed in the right direction to doing this with html5 and javascript WITHOUT jquery. I understand that it might be easier with jquery, but I need to figure out how to do it without for the time being.
Would there be such a thing as window.addEventListener("AJAXload", someFunction(), false) ???
Instead of adding an event listener programatically, you could possibly insert a bare Javascript function at the end of your AJAX'ed content. This would be run when the content is loaded, calling something in the parent window.
AJAX BLAH BLAH BLAH
<script type="text/javascript">
childContentLoaded(); //or whatever you need
</script>
you may also need to add "parent".functionName()

jQuery not working when the page loads [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have built a simple page on my localhost and then I have uploaded it on the net. When the page is viewed from local machine, all jQuery interactions works well without any problem. But when I view the hosted page, nothing happens. It seems a plugin + jQuery are not loaded properly, though I see them loaded (using firefox view source code, I check the scripts address and see their source without 404 error).
I appreciate any help. Here is the address:
http://tarjom.ir/demo/niazer/
The jQuery interaction is that when the user clicks on the search bar, a box slides down which contains many search-categories.
And also the thumbnails at the bottom of the red line moves when mouse hovers it. Now, you probably wouldn't see any of these stories.
The page is written using codeigniter.
EDIT EDIT
the scripts and CSS are loaded automatically using a library written for codeigniter. But the generated HTML markup for browser is as follows:
<script type="text/javascript" src="http://tarjom.ir/demo/niazer/js/blue/2-prettyCheckable.js"></script>
<script type="text/javascript" src="http://tarjom.ir/demo/niazer/js/blue/1-jquery.js"></script>
<script type="text/javascript" src="http://tarjom.ir/demo/niazer/js/blue/mtSlideElement.js"></script>
prettyCheckable is a jQuery plugin, you need to include it after you call jquery, change the order you are including the scripts so it looks like this:
<script type="text/javascript" src="http://tarjom.ir/demo/niazer/js/blue/1-jquery.js"></script>
<script type="text/javascript" src="http://tarjom.ir/demo/niazer/js/blue/2-prettyCheckable.js"></script>
2-prettyCheckable.js has a semicolon as its first character and there is no method called prettyCheckable in it. Did a few lines get cut out of this script by accident?
Your pages has two 'html', 'head' tags, you might want to remove them. And put all those javascript into a single.js file and call include it just before tag.
There is are definition for prettyCheckable();
You have loaded two jQuery, at first jQuery v1.10.2 and then prettyCheckable.js and then again jQuery v1.10.1, this is the problem because, once prettyCheckable extended the core jQuery and then you loaded again another jQuery and it's completely new. This the order
http://tarjom.ir/demo/niazer/js/blue/1-jquery.js // loaded
http://tarjom.ir/demo/niazer/js/blue/2-prettyCheckable.js // jQuery.fn extended
http://code.jquery.com/jquery-1.10.1.min.js // old jQuery replaced

How to call a external javascript function from aspx page? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a javascript file file.js and I have a function FunctionfromJSpage() in that js page, first from onclick I was calling the function aspxPageFunction(); then from this function I need to call FunctionfromJSpage(); which is located in file.js.
I tried like this in default.aspx
<head>
<script type="text/javascript" src="../page/file.js"></script>
<script type="text/javascript">
function aspxPageFunction() {
//my code..
FunctionfromJSpage();
}
</script>
</head>
But I am unable to call that function.
harish,
I think what you're looking for is to add the function you've now defined (as Quentin pointed out) to an attribute of an existing asp control. For example:
<td>
<asp:Button ID="Button2" runat="server" OnClientClick="YourFunction(); " Text="ClickMe"/>
</td>
You can do all sorts of things using this kind of methodology. It all depends on what you want to do. If you're trying to get something to happen when a user puts text in a textbox, you'll need to research the OnTextChanged event, dropdowns have the onchange event..perhaps a crash course in asp events might be useful to help you understand more about where to attach such things.
For client side (javascript events).
For server side - what we're talking about here - (asp events).
It looks like you're just starting to figure out the client server relationship and what you need to do to make things happen (I could be very wrong there though). If this is the case, I wish you well! I agree with the other posters - you should explore Google and this site a bit more, as these are VITAL resources to finding breakthrough on your coding endeavors.
-sf
The code you have in your script element defines a function.
You say that you have defined it in file.js. To call it you just callFunction().
<script type="text/javascript" src="../page/file.js"></script>
<script type="text/javascript">
callFunction();
</script>
Add the onload attribute to your body, this will call your function when the page loads <body onload="callFunction()">
or in codebehind
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "scriptKey", "callFunction();",true);
Have a look at this great article http://www.codeproject.com/Articles/11098/Use-Call-RegisterStartUpScript-RegisterClientScrip

How to run scripts loaded dynamically with javascript

I was wondering if there is a way to execute script within a ajax dynamically loaded content.
I've searched the web and this forum also an find a lot of answers, like
[Running scripts in an ajax-loaded page fragment
[1]: Running scripts in an ajax-loaded page fragment [1]
But none of this seems to work fine for me.
I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.
For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:
//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,
$ajax([..]) //THEN
.ajaxSuccess(function(){
// LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
$(".script_target").each(function()
{
//DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
//EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
//WILL FIRE A SCRIPT RELATED TO drop_down CASE.
});
});
I know this is an ugly solution but i didn't came up with nothing better than this.
Can you help to improve this method?
Maybe there's a way to let the browser fire script within the loaded page automatically?
PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.
Thanks in advance.
If I understand you correctly :
you use "load" to retrieve html content from the server, and you add it to the page.
later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
but, depending on the markup retrieved, you want to do something different in the ajax callback
So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?
Otherwise maybe something like this would work :
In the callback of the "$.load" function, use $.data() to attach more information to created dom object
In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?
Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.
Hoping this helps.
EDIT : After your comment, it might be related to the selector you use when calling $.load().
There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :
$('#b').load('article.html #target');
Could this be your issue ?
Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).
This way, "loading" a page would be something along the lines of :
$.load("url_of_a_page_markup.html", function () {
require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
TheJsModuleForThePage.doSomething();
});
});
If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.
Hoping this helps.
If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.
Have you considered a module loader like require.js or Lab.js?
There are many other people asking similar questions:
does anyone knows good ajax script loader
Where are scripts loaded after an ajax call?
getting jQuery scripts and content through ajax dynamically
dynamic script loader in JS
Edit: I think I misread your question. Will try and come up with a better answer. Sorry!
Best of luck to you!
I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).
$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});
To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
(function() {
$('#myButton') // My button element
.button() // Initialize it as a JQuery UI button object
.click(function (){ // Hook up the button click event
$('#correct')[0].play(); // to play a sound in an <audio> tag
});
});
</script>
</head>
<body>
This is my help file, this is my code. This is for reading, this is for fun.
<button id="myButton">Button Text</button>
</body>
</html>
The dialog would load and the HTML displayed, but the embedded script did not execute.
I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.
This:
<script>
(function() {
...
});
</script>
Became:
<script>
(function() {
...
})(); // Immediately invoke
</script>
Niceness.

Categories