way to load javascript code in web page - javascript

I prepare a project with a simple webpage, canvas, and javascript files that run game in the canvas. I want load my code when page starts, what is best way?
put body onload?
startup code in body of .js file (not in function)?
attach to window load event?
use some jquery capability?
Thanks!

You can attach to when the page loads using jQuery like this:
$(function() {
// Your code here.
});
If that's the only thing you'd be using jQuery for, though, I'd probably stick with your third option you listed there.

Javascript and jQuery code is generally best put right before the </body> tag.

Use $(document).ready
$(document).ready(function() { code goes here; } );

Since you are using jQuery, you should use the facilities it provides..
$(document).ready(
function(){
/*You code goes here..*/
});

Related

How do I get a jquery function to run when the page is loaded?

I'm trying to create an html page that uses jquery to populate a table when the page loads. I have the function that gets the data, but currently for testing I just attached it to a button that I'm clicking to get the table to appear.
How do I get a jquery function to run when the page is loaded? In case it isn't obvious I'm a complete beginner when it comes to Jquery, so this may be something really obvious, but I've been trying to google it and I can't find a solution.
This should do the trick
jQuery(document).ready(myFunction);
function myFunction(){
// logic goes here
}
jQuery(document).ready(function(){
//some logic
newFunc();
//logic
});
function newFunc(){
//logic
}
However you can write code anywhere inside <script> tags and it will execute directly after including the jQuery file. But, the may not be as effective as above because at that time dom may or may not be created. So, better go the above way .. as it will only execute when page is loaded and DOM is created.
Are you looking for something like this. You can do this in regular JS.
document.addEventListener('DOMContentLoaded', function() {
console.log('document loaded');
});
But be aware this doesn't cover you from other dependent file loading like the js and png and others . They get loaded asynchronously . this just cover you for the dom content load

Do I still need $(document).ready(function(){ })?

I've been developing in javascript for a few months and I have been using $(document).ready(function(){ at the beginning of all my scripts. I've noticed other folks don't use this in their scripts but I can't seem to get mine working without it. I'd like to keep my code cleaner, but for all my google searches I can't seem to figure out how to get rid of it.
I know it tells the browser to execute my script as soon as the page loads but is there something global I can set so that I don't need to explicitly tell the browser to execute each of my scripts when the page loads? Or is it a more global problem with where in my html files the scripts are located?
You're needing document.ready probably because you're interacting with the DOM before it loads. How can the script manipulate elements that are not there yet?
If you stick your script at the end of the file you will not need it. It's also good practice to do so for a lot of Javascript files as they can take time to process (especially if they're hosted externally). Putting them at the end of the file often speeds up the page load time.
All $(document).ready(function() { ... }); or $(function() { ... }); does is wait for the document to be ready for manipulation. You should use $(document).ready(function() { ... }); or $(function() { ... }); if your scripts are inline or in the <head /> section because JavaScript executes in the order in which it appears on the page otherwise.
To do away with $(document).ready(function() { ... }); or $(function() { ... });, simply move your scripts down to the bottom of the page after all of your content, right before the closing </body> tag.
Putting the scripts at the bottom is really a best practice anyway. For this and other best practices, I recommend you take a look at Html5Boilerplate and Yahoo! Best Practices.
the $(document).ready() convention is part of jQuery, not just JavaScript. From their' documentation on the ready function:
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
So yes, it is required. jQuery does come with a shorthand for this though, so you could do the following:
$(function() {
//jquery code
};

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.

Load javascript after page load

I have an external javascript that contains something like:
document.writeln("<script type='text/javascript' src='...'></script>");
In the original html i have something link
<div id="banner">
<script type="text/javscript" src="<the external javascript above>"></script>
</div>
How can i load that delayed?
I've tried using window.setTimeout and append that javascript but its not working.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
Thank you.
You can call your injection code on window.onload.
window.onload = function() {
inject();
doSomethingElse();
};
window.onload will wait until all assets have finished downloading, such as images and scripts. After scripts are downloaded, you can inject your code to page.
Maybe a better way to do it would be to add a delay to the script.
Also, if you use something other than 'document.writeln' for example:
$('#banner').append(...);
you can better direct where it goes.
There is an open source javascript library for doing this kind of thing: http://labjs.com/
I have used it in the past and it worked very well.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
That is not entirely true. Especially if the div is empty you could simply use: document.getElementById('banner').innerHTML = "<h1>HTML-Output here.</h1>"
Bukko's answer would work as well if you are using jQuery. My answer is pure Javascript. With this newfound freedom you should be able to simply put the loading of your script at the bottom of the page or use a custom body.onload() function
Edit: or simply follow Samet's suggestions in conjunction with the .innerHTML. Hope this helps.

a solution to include jquery & js in the end of the html while at the same time a control which is included in the middle requires $(document).ready

i am building a website using asp.net mvc and jquery.
as a best practice its known that including javascript should be done at the end of the html page.
so i basically include jquery.js and other js files in the end of the html before the /body tag.
now i have some controls which are included in the page as partials. and they need to add functionally to $(document).ready.
but i write the code as a script tag in the partial then the jquery library wont be even included at that time and i cant include this javascript at the end of the html from within the partial. since the partial is included in the middle of the html.
Move all javascript in single file(you may exclude jQuery file) and move it to the bottom.
If you are talking of good practice then, then writing inline javascript is not a good practice too.
So I would suggest move all your java script to single file,there are many tools available that merge multiple javascript files and crunch them, use those!!
Edit1
You may try this:
//define this at before body (or at the beginning of body)
var arrReadyCollection = [];
Inside controllers:
arrReadyCollection.push(site.module.Dialog_AcceptChanges);
arrReadyCollection.push(some_thing_Else);
At the end, after jQuery file
for (i=0;i<arrReadyCollection.length; i++)
{
var fn= arrReadyCollection[i];
$(document).ready(fn);
}
Note: this is not recommended way, its just way you can solve your problem
You should use a javascript loader like LABjs.
You can use it to run javascript when certain libraries are loaded and run.
<head>
<script src="lab.js"></script>
</head>
<body>
<script>
// $LAB uses async loading, no need to deferr to the end of body
// keeping a reference to the $LAB deferred is important, so we can
// use it from within partials (see below)
myPage.$LAB = $LAB
.script('someScript.js')
.script('someOtherScript.js')
.wait(function () {
// your scripts are loaded!
});
</script>
</body>
In your partials you can hook into LABjs, eg like this:
<script>
myPage.$LAB.script('jQuery.js').wait(function () {
// jQuery was loaded!
// if jQuery was loaded already by another partial or your main layout
// it will not be loaded again, but the callback will fire immediately!
});
</script>
That beeing said you really should follow the advice given by Praveen and tie your javascript files up as much as possible. Each request to your server will cost time and decrease the responsivness of your website.
Either fix your "control" files so that they don't require inline JavaScript, or else include jQuery at the top of the file.
You could also write a small "$" function of your own that you'd include before jQuery (and at the top). However, you'd be better off fixing those controls anyway.
Another possible solution would be to add a script tag dynamically from within the partial. This however could get messy if you want to run more than a few lines of code, eg:
<script>
var script = docuement.createElement('script');
script.innerHTML = "$(document).ready(function () { doSomething(); });";
document.body.appendChild(script);
</script>
This should run after the jQuery (which should be already somewhere at the end of the body) was loaded and run.
UPDATE:
This does not work, I assumed that inserting script elements in a DOM that wasn't ready yet wouldn't execute before the DOM is ready.
Use CDN's and quit obsessing about doubtful optimization. From the excellent jQuery in Action book, sec 1.22
NOTE For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.

Categories