Reputation: 182
I'm a newbie and i'm playing around trying to achieve something using javascript.
I have a function which i need to take effect once my page loads but i don't want to use <body onload="init()"
is there another alternative?
<script type="text/javascript">
function init() {
container = document.createElement('div');
<script>
<body onload="init()">
</body>
Upvotes: 10
Views: 11642
Reputation: 487
I am new in programming but i think u can do something like this: With Jquery
$(document).ready(function(){
// code loaded..
});
Without Jquery
// this code is bad to practise
<script type="text/javascript">
function init() {
// Put your code here
}
window.onload = init;
</script>
Upvotes: -3
Reputation: 182
Well, you can use jquery, but you have to include it in your head manaully or with
<!-- Google CDN -->
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
if you want to use Google CDN, or
<!-- Microsoft CDN -->
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head>
for Microsoft CDN. Now, you can use jquery in your webpage. So write in your head
<script type="text/javascript">
$(window).on('load",function(){
// your code
});
</script>
Of course, you need to know how to use jquery to use this solution. However, you can use javasript too, but I suggest you to start learning jquery: is very useful.
<script>
window.onload = function() {
//your code
}
</script>
This should be the right way ;)
REALLY IMPORTANT: this functions are called when your document is starting loading! If you want to apply something at the end of the loading of the page (better solution to improve loading speed) use
$(document).ready(function(){
//your code
});
in jquery, or
document.addEventListener("DOMContentLoaded", function(event) {
//your code
});
in javascript
Upvotes: 1
Reputation: 36438
Call it from a load
handler:
function init() {
container = document.createElement('div');
// ...
}
window.addEventListener("load", init);
Upvotes: 10