This one must be very simple. An external javascript file contains:
function Hello() {
alert('Hello');
}
It is getScript()ed and then a contained function is called
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.getScript('myscript.js');
Hello();
</script>
I get:
ReferenceError: Hello is not defined
But if the script is referenced in an HTML <script> tag it works as expected
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">
Hello();
</script>
What I am missing? How to reference objects created in a getScript()ed script? The reason I want to use getScript() it to load the script on a ready() event.
The issue is that the $.getScript() function is asynchronous. When you call the Hello() function immediately after, the script is not yet loaded so the function is not available.
Loading scripts with regular <script> tags happens synchronously, so if you want to duplicate that behavior you have to disable the async option in your Ajax call.
getScript alone does not support this, so you can do this using an $.ajax call with the appropriate options:
$.ajax({
url: 'myscript.js',
dataType: 'script',
async: false
});
This will block the browser until the script is loaded.
However, a better technique is to use a callback, which $.getScript() does support:
$.getScript('myscript.js', function() {
Hello();
});
You need to wait for the response:
$.getScript('myscript.js', function(){
Hello();
});
Related
I am writing a script using pure js involving a js snippet that is copied into cleint websites. When invoking a pure js function myfunction() like below the function will run, no need for document.ready, onload etc:
<body>
<script>
function myfunction(){}
myfunction()
</script>
</body>
So my question is if I load an external file like this below, will the js function execute with simply myfunction() and across all browsers.
<body>
<script type="text/javascript"async=""src="anotherwebsite.com/jsfile.js"></script>
</body>
jsfile.js contents
function myfunction(){}
myfunction()
What happens If you dynamically load in a <script> tag it will be executed asynchronous by default. So the code will be executed and myfunction will be invoked. If you want your code to be synchronously you can set the async attribute to false like this:
<script type="text/javascript" async="false" src="anotherwebsite.com/jsfile.js" ></script>
More on async in MDN Docs.
Hello I want to call javascript method directly from jsp.Here is my dummy code in this javascript method print1() is not calling.
<html>`
<body>
<h1>hello</h1>
<script>print1()</script>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>
</body>
</html>
Solving this can help me to great extent.
Note-I can't call it using onload as this is only dummy code I have to apply logic to some other code
First, there are a few syntax errors in your code that need to be fixed.
Then, You will need to call the function after it is defined (or in the same <script> tag). Function hoisting does not hoist print1() in time. That is because the browser tries to execute the script as soon as it encounters it. This means when the browser sees <script>print1()</script>, it is not even aware of the rest of the file.
So you need to invoke print1() after the function is defined. In addition to the solutions in comments and the other answer, another option would be to put the script in a separate file and invoke it with defer.
printFunc.js:
print1();
In the html file:
<script src="printFunc.js" defer></script>
This will invoke print1(). Note that defer does not work if the script is not external.
Just for fun (and To see how the browser goes through <script> tags), you can even invoke the function via setTimeout:
<script>
setTimeout(function(){ print1(); }, 3000);
</script>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>
There are two options to fix the issue:
Option1: Move the call <script>print1()</script> to the end of the file (i.e., define the function first before the call and look here for clear explanation on this)
Option2: Call it during the body onload as shown below:
<body onload="print1()">
</body>
Firstly its that you can call it in body tag as "onload", Secondly "getElementsByTagName" returns array so you have to tell at which array position you want to make your change
<html>`
<body onload= "print1()">
<h1>hello</h1>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p")[0].innerHTML="hey";
}
</script>
You can do this way also
<html>`
<body>
<h1>hello</h1>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p")[0].innerHTML="hey";
}
</script>
<script>print1();</script>
</body>
</html>
HI i am facing some problem while calling function from index.html on load event
it return error readjson is not defined in console.
index.html
<script type="text/javascript">
$(window).load(function () {
readjson('a','s');
});
</script>
main.js file
<script type="text/javascript">
function readjson(val1,val2){
//some code
}
</script>
Can anyone tell me why it is not able to call, i have link main.js file to index.html
JavaScript files shouldn't include any HTML.
Remove <script type="text/javascript"> and </script> from main.js.
You should see an error when that file is loaded (along the lines of Unexpected token <).
Call it like this inside the js file without the "script" tag :
function readjson(val1,val2){
//some code
}
In index.html you need the "script"
And follow the advice given in the comments, always include first the .js file and then the function in the index.html
Did you add jquery link properly??
If not, you should add jquery link for $(window) to be called. such as..
<script src="http://code.jquery.com/jquery-latest.js"></script>
If you actually have two script declarations as you are showing here the the window load will fire first. It then look for your function, which has not been created yet. That's why you are getting undefined.
You could have one script declaration on the page and place your function in the load function.
<script>
$(window).load(function () {
readjson('a','s');
function readjson(val1,val2){
//some code
}
});
</script>
Remove tags from main.js:
<script type="text/javascript"> and </script>
and remember to include jquery and main.js with:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
<script src="test.js"></script>
My doOnLoad function is not running when page is loaded. Any idea what is wrong with my code?
<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../js/events.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//Not working. How do I get this function to run when the body is loaded?
$("body").load(function() {
doOnLoad();
});
//doOnChange is running properly
$('#mydirection').change(function() {
doOnChange();
})
});
</script>
From http://api.jquery.com/ready/:
The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.
I am using google ajax api
How can I load custom js which depends on libs loaded by ajaxapi?
You could define a function that inserts the script object into the DOM like
<script type="text/javascript">
function loadMyCustomJavaScript() {
var script = document.createElement("script");
script.src = "http://www.example.org/my.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
</script>
and either use it as google.setOnLoadCallback
<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
google.load("jquery", "1");
google.setOnLoadCallback(loadMyCustomJavaScript);
</script>
or, if you want to load it with a specific Google library that you load, as a callback for that method, ie.
<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
google.load("maps", "2");
google.load("search", "1", {"callback" : loadMyCustomJavaScript});
</script>
Update: Based on your comment, you could try to use jQuery.getScript which provides a callback function for the (externally) loaded JavaScript code. According to HubLog: Google, jQuery and plugin loading, you may have to use window.setTimeout to delay the execution of a function until the script(s) has/have eval'd.
Since jQuery and it's plugins are probably loaded asynchronously, you may need to use unobtrusive JavaScript instead of using jQuery/plugin functions in the HTML code directly.