My java script file is referenced in the body of my base template:
<body>
...
<script type="text/javascript" src="/static/js/test.js"></script>
</body>
I an another template which extends the base template, the java script function draw() defined in test.js can be invoked by using the onclick Event. Sadly I only get a picture when clicking over the canvas area. But invoking the function by <script> draw(); </script> occurs the following error: ReferenceError: draw is not defined How can this possibly be?
...
<div class="panel-body">
# works perfectly fine, somehow the function can be accessed
<canvas id="canvas" onclick="draw()" width="300" height="10"></canvas>
# occurs an error, somehow the function can't be accessed anymore...
<script> draw(); </script>
</div>
...
I use python flask framework for back end programming.
Because you initialized the <script> at the end of the webpage, and you call draw() before it's initialized.
I would put it in the head tag:
<head>
...
<script type="text/javascript" src="/static/js/test.js"></script>
</head>
You said that for the onclick it works, of course it works, when you click on the canvas the draw() function is already initialized.
The order of the script is what matters here. Scripts are loaded in the order encountered in the page.
Since "draw()" is a direct call, I presume this is defined before the tag in the body, so this why the browser says it is not defined. On the other hand, the onClick of the canvas can happen only after the page is loaded, so that's why it is working there.
I recommend to put the javascripts of a specific page below the scripts of the base template somehow (you have to use maybe you'll need two separate references for that), or you can use other techniques like JQuery's $(document).ready().
Here is a very similar question, hope that helps:
load and execute order of scripts
Why won't you wait for the document to load? That would be the proper solution to this problem.
document.addEventListener('load', function (){
draw();
});
Sorry about the ugly indentation, I'm using my phone
Related
It is well known to everyone that using defer is an efficient way to minimize the loading time of a website.
In my project, I am using Vue (included in the header using defer) and in a circumstance, I want to use a component that is created by another person. When I try to do Vue.Component(...) in the body of the HTML, it says Vue is undefined. It seems that my script in the body is running before the external script has been loaded. Is there any way to fix this issue?
I tried to do document.onload, but the function itself is not working.
PS: Just to be clear, the external script is referring to my js file where Vue is defined and I am not talking about the third party library at all.
Instead of document.onload you need to use window.onload or document.body.onload.
But an even better way is to wait for the load event on <script> tag:
<html>
<head>
<script id="vue-script" src="vue.js" charset="utf-8" defer></script>
</head>
<body>
<script type="text/javascript">
function onVueLoaded() {
Vue.render();
}
if ('Vue' in window) {
onVueLoaded();
} else {
var script = document.getElementById('vue-script');
script.addEventListener('load', onVueLoaded);
script.addEventListener('error', () => console.warn('failed to load Vue.js'));
}
</script>
</body>
</html>
Here I also added a handler for the error event if you wanted to explicitly handle loading errors.
I have a layout file where i included Jquery just before closing tag.
//layout.handlebars
<!DOCTYPE html>
<html>
<head></head>
<body>
{{{body}}} // renders the body content
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
I also have a page specific javascript(helper.js) that makes an Ajax call.
<div>Some sample data</div>
<script src="/js/helper.js"></script>
but the problem here is jquery is loaded at the end of the page but i am referring to it in the external javascript before jquery is loaded. which shows me '$' is not defined and i know that is obvious.
One solution to this will be like adding jquery to the head section but that is not what i want.
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Any help is much appreciated!!
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Yes, I assume you already understand the cause of the issue. As you see below the final content is ..
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>Some sample data</div>
<script src="/js/helper.js"></script> <!--Jquery is not loaded yet, and hence $ is undefined -->
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
As you already know one option is to move jquery anywhere in the HTML but make sure its loaded before any other jquery dependent files. Now since you don't want to take this option. we have another option.
Solution:
Our only aim is to make sure the jquery library is loaded prior to any other jquery dependent files.
We can get the files on document.ready using $.getScript()
$(function(){
$.getScript( "/js/helper.js", function( data, textStatus, jqxhr ) {
console.log( "Load was performed." );
});
});
Extras: If you feel this is a overhead and you cannot add this code to all the files in your page (since there can be too many files ), You can write a generic function and a global array variable , This function will check for file paths in the array and execute each one synchronously and remove from the array. Make sure this generic function is called in every document.ready event.
One Solution is that You can put the jquery script at the start of body tag before {{{body}}} section .. In this way your helper script will be rendered after jquery and your problem will be solved .....
Well its not pretty but you could use some kind of test and wait loop something like
<script>
(function test(){
if( window.jQuery ){
//your jQuery code
} else {
setTimeout(function(){ test(); }, 200);
}
})
</script>
See the source of http://marakana.com/s/post/1096/samples/try6.htm
It defines a function and calls it on load of document. (Which is the final step of this tutorial)
I tried to put it into a seperate JS file.
Runs correctly only if I call onload both in JS and in HTML.
But not only body onload or only from JS. I guess I am doing something wrong.
So, following works:
<head>
<script src="Scripts/makeWYSIWYG.js" type="text/javascript"/>
<script type="text/javascript">
window.onload = function () {
makeWYSIWYG(document.getElementById('editor'));
};
</script>
</head>
<body onload="makeWYSIWYG(document.getElementById('editor'));">
Why do I need to call the function twice?
I only have the function definition in "Scripts/makeWYSIWYG.js"
function makeWYSIWYG(editor) {
...
return editor;
};
Thanks,
There are no reason to call the function twice. The is enough.
With the first window.onload you could be changing a former function callback assignment (i.e. in a imported script).
The problem was actually the closing tag, "/>", here:
<script src="Scripts/makeWYSIWYG.js" type="text/javascript"/>
I should have written:
<script src="Scripts/makeWYSIWYG.js" type="text/javascript"> </script>
I guess the second script was helping the tag to be closed and making it run...
More info here: Why don't self-closing script tags work?
A simple script tag inside the body tag doesn't seem to work. The alert doesn't get triggered in the code below:
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{>main}}
</body>
Any idea why?
Edit:
Just tried it with a fresh meteor app, no alert tag still:
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
Weird thing is when I copy paste the source of the html, made a new html page, and the alert will work.
Edit3: I deployed this app here: http://alert-in-body-test.meteor.com/
Do you get an alert box?
This question is still relevant in the current version of Meteor (version 0.5.4) so I wanted to describe how to include script at the end of the body.
To execute javascript at the end of the body, register a Handlebars helper and put the relevant code there, like this:
In client.html:
<body>
{{renderPage}}
{{afterBody}}
</body>
...
In client.js:
if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('afterBody', function(name, options) {
$('body').append('AFTER BODY');
});
}
(For a great description of why this is required, see Rahul's answer to a similar question here: https://stackoverflow.com/a/14002991/219238 )
Its working for me
in onrender call this jquery
$.getScript('yours url')
It should work.
I have just pasted this inside one of my projects and it worked.
Your {{>main}} is strange for me tough. Also make sure that <body> is inside <html> tag.
Meteor is constructing the entire DOM from Javascript by rendering your page as a template -- the 'source' for your page as seen by the browser is basically:
<script type="text/javascript" src="/5a8a37bef5095c69bcd3844caf3532e1ba6d49bf.js"></script>
I can't find a definitive page stating that embedding a script tag in a template like this won't cause it to be executed, but it definitely feels against the spirit of what the framework is trying to achieve.
If the point is to achieve a clean separation of your markup and logic then why put it in the template. A better solution would be to use the meteor.startup call
Instead of looking the rendered html at developer tools, try looking the real downloaded html.
You will find a (probably) empty tag, with tons of script tags inside the .
In other words, the body of your meteor application is not the body of the final html, it's just your main template.
Instead, this ton on scripts shipped by Meteor, will load your templates.
So, your code will not run, cause it's been placed there. It's like when you manipulate DOM (with jQuery, for exemple), placing a script tag in DOM, after it's loaded. This script tag will not run.
I am trying to load 2 javascript events/functions in the body onload as follows :-
<body onLoad="getSubs(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);getTags(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);">
Whenever I load using 2 functions the first one aborts - but if I just load the one it works fine - am I doing something wrong is it no possible to put 2 functions within the onload?
try this:
<html>
<head>
<script language="javascript">
function func1(){
//the code for your first onload here
alert("func1");
}
function func2(){
//the code for your second onload here
alert("func2");
}
function func3(){
//the code for your third onload here
alert("func3");
}
function start(){
func1();
func2();
func3();
}
</script>
</head>
<body onload="start()">
</body>
</html>
Multiple onload
Just do it from java script instead, one of the link shared into a comment explains well why it is best to use this approach over inline attributes.
<head>
<script>
document.body.onload = function() {
getSubs(...);
getTags(...);
};
</script>
</head>
<body>
...
</body>
I would avoid at all cost to have inline javascript, that is what you did in the code of your question: add javascript within an HTML attribute.
Best practice is to add your javascript in a separate file, see the related question on this principle What is Unobtrusive Javascript in layman terms?
So you'd have an other file called for instance "myjsfile.js", then you reference it from your HTML page
<script src="./path/to/your/myjsfile.js"></script>
Here is the answer to where to place this reference: Where to place Javascript in a HTML file?
Your "myjsfile.js" file would simply have:
window.onload = function(){
getSubs(...);
getTags(...);
};
Another thing to avoid: add javascript within the same HTML file. The reason is also based on the same principle of unobstrusive javascript. What is Unobtrusive Javascript in layman terms?
But I guess there are corner cases where you may want to do that.
If you really have to, do use window.onload instead of the inline javascript onload="...", see why here window.onload vs <body onload=""/>
Just add the following to your HTML file:
<script type="text/javascript">
window.onload = function(){
getSubs(...);
getTags(...);
};
</script>
Here is the answer to where to place this code: Where to place Javascript in a HTML file?
Note: Yes, in the same place as where you would put the reference to an external javascript file
Another thing: I do not know where your getSubs() and getTags() functions are defined. But if you want your code to work, it needs to call these functions after the file (or part of javascript) that defines them has been loaded.
In short: make sure the javascript file containing the definitions of getSubs() and getTags() is referenced before your code.
One thing that you could do is create a new JS function that accepts the document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value parameter and call the two functions in the newly created function.
I tried calling two functions using the below code and it worked fine for me.
<html>
<body onload="callStart();callAgain();">
<script type="text/javascript">
function callStart() {
alert('First');
}
function callAgain() {
alert('Again');
}
</script>
</body>
</html>