Should raw javascript be in a .js file - How to include? - javascript

Suppose I have a page such as the following
<html><head></head><body><!--STUFF-->
<script>
if(SomeBooleanVariable) {
$.getScript('js/file.js');
}
</script>
</body></html>
and my file.js file simply contains raw jQuery events with no wrapping. It is exactly as follows:
$(document).on("eventHere", "classHere", function(e) {
//Stuff
});
$(document).on("eventHere", "classHere", function(e) {
//Stuff
});
This is simply not working. When I include the contents of file.js directly into the HTML it works fine however the JS does not seem to be included properly. I have tried putting "alert(3);" at the top of file.js but it does not fire. I have tried the following:
$("head").append("<script src=\"js/file.js\" />");
$(document).append("<script src=\"js/file.js\" />");
-and-
document.write("<script src=\"js/file.js\" />");

If you want to load that .js file dynamically, change your code to this:
if(SomeBooleanVariable) {
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log(textStatus);
})
.fail(function(jqxhr, settings, exception) {
console.log("Triggered ajaxError handler.");
});
And see if you get any error in console
It may be, that you are, for example, using mod_rewrite and jQuery tries to load script relative to the "folder" your subpage is in. Example: you are # http://www.example.com/link-to-subpage/. In this case, jQuery will try to load http://www.example.com/link-to-subpage/js/file.js, while it resides # http://www.example.com/js/file.js. In this case, use an absolute path. So, instead of:
js/file.js
write:
/js/file.js

Related

javascript function doesn't responding

Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().
function checkJs()
{
debugger;
alert("your output!!!");
}
My code:
<div id="mydivid" style="background-color:lightblue;">
STAGE
</div>
<input type="button" id="btnid" value="Load Data" />
When i click a button , Its just call the jQuery click function
$(document).ready(function () {
$("#btnid").click(function (event) {
debugger;
$.getScript('mydata.js', function() {
// debugger;
checkJs();
});
});
});
I used initialy 1.12.4.js library file in the head tag
and i added my external js file in head tag.
what is the problem in my code. why the button click did not reached the external method.
1.Make sure that jQuery library added before your external java-script file.
When you ensure the first point do like below:-
$(document).ready(function () {
$("#btnid").click(function (event) {
checkJs();
});
});
2.If you want to use $.getScript() then do like below:-
$(document).ready(function () {
$("#btnid").click(function (event) {
$.getScript('mydata.js').done(function(data, textStatus) { // check the file path of mydata.js is correct or not?
checkJs();
});
});
});
The above code will work only when you have jQuery library added before this code and you remove the external JavaScript file path from your head.
Note:-
data:- returned data from external script
textStatus:- status of the call to external script (plain-text like "Success")
For more knowledge check this link:- jQuery.getScript()
You can directly call your function without getScript if you have already included the mydata.js in head.
If not, and want to do it with getScript then make sure you are giving correct path, load js in done callback and if still not then check if calls goes to fail callback.
$(document).ready(function () {
$("#btnid").click(function (event) {
debugger;
$.getScript('mydata.js').done(function(data, textStatus, jqxhr) {
checkJs();
}).fail(function(){
if(arguments[0].readyState==0){
//script failed to load
}else{
//script loaded but failed to parse
alert(arguments[2].toString());
}
})
});
});
Done callback has 3 parameters with has following values in it.
data: has the returned data(script)
textStatus: it returns the status in plain text, e.g. "Success"
jqxhr : its jqXHR object, which is a superset of the XMLHTTPRequest object and has the "status" property which returns status code.

jquery .load() does not load external JS

I am loading external content into a div element using jquery.load() without a selector. If the content loaded has embedded JS, the JS works as expected. HOWEVER, if the content includes a script tag with src=path-to-js-code the js-code is not loaded.
Am I correct in this observation and if so is there a good solution other than embedding the JS in the loaded content?
EDIT :
A few clarifications and observations:
To load the content I am using
$("#DivId").load("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking and post processing code
});
Changing the load code to:
$.get("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking
$("#DivId").html(response);
post processing
});
Does not seem to change the behavior (more on the behavior below)
I have not tried parsing the response to retreive the script src and then using getScript().
Now more on the behavior...
Using Firefox, it seems that the external JS is loaded but only if it has been about 2 min from the last load. I do not see an attempt in Firebug unless the refresh is about 2m after the last load of the external JS. (weird). When I was making JS code changes and hitting refresh, it was not loading my new code and thus the original question.
So i will withdraw my question in light of this clarified behavior (2m caching?).
Thanks.
Both the .load() and .html() jQuery methods utilise the .innerHTML property. This won't execute scripts added with <script> tag. Use a regular AJAX call e.g. .get() then in the callback use .append() to add your HTML string and the scripts will run once it's parsed e.g.
$.get("path/to/content.php", function(response, status, xhr) {
// error checking
$("#DivId").append(response); // Any <script> tags in the response string will execute
// post processing
});
Thing is you need to make sure you're running trusted code if it's added by .append()
I was wondering you can get the script src in the response text of $.load method with regular expressions, then use $.getScript() method to load the script, maybe something like this:
$("#DivId").load("path/to/content.php", function(response, status, xhr) {
var regexp = new RegExp('script.*?src="(.*?)"'),
execresults = regexp.exec(response);
if(execresults.length > 1)
{
// the first result is the entire match including
// the 'script..src=', so abandon it
var matches = execresults.slice(1);
$.each(matches, function(){
$.getScript(this, function(){
// do something after load script
});
});
}
});
Hope this can help
This is the easy way to load an external JS to your jQuery
$.ajax({
type: "GET",
url: "path/to/content.php",
dataType: "script"
success:CallbackFunction(response, status, xhr)
});

Impossible to load file from a relative path using jquery

Using jquery I'm trying to load a html file(page.html) using jquery from an other subfolder(folder2\index.html) of the parent folder(project) ; but it gives the following error : "InternalError: too much recursion" .
Here is the hierarchy of the sample :
|-Project
|-folder2
| |-page.html (html to load)
|
|-folder1
|-index.html(page where the loading script is called from)
Here is the code I'm using
$( "#destination-ressource" ).load( "../folder2/page.html", function( response, status, xhr ) {
//do somthing
});
when xhr.statusText is inspected it gives the following message: "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
I also tried to replace
"../folder2/page.html"
by
"./folder2/page.html"
but it doesn't work .
If your script are in separate file js then the relative path is from the path of that script, not from your html file

How to insert external javascript files in meteor js (0.9.2.2) template

I am using following code to insert javascript files in template :
_.each([
"/assets/global/plugins/jquery-1.11.0.min.js",
"/assets/global/plugins/jquery-migrate-1.2.1.min.js",
"/assets/global/plugins/jquery-ui/jquery-ui-1.10.3.custom.min.js",
"/assets/global/plugins/bootstrap/js/bootstrap.min.js",
"/assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js",
"/assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js",
"/assets/global/plugins/jquery.blockui.min.js",
"/assets/global/plugins/jquery.cokie.min.js",
"/assets/global/plugins/uniform/jquery.uniform.min.js",
"/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js"
], function(script, ready) { jQuery.getScript(script, function (data, textStatus, jqxhr){
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
})
});
I am getting following results (only one sample out of 10), all 10 files showing success messages :
(function(){var t=[].slice;!fu"[…] admin.js:63
"success" admin.js:64
200 admin.js:65
"Load was performed."
But when I see "View Generated Source" in Firefox developer tool, I can't see any inserted JavaScript files in html code. Can some one guide me what I am doing wrong and how it can be rectified.
The code works fine for me. jQuery.getScript() does not seem to change anything in the DOM, it simply runs the code virtually. Try adding a file that has console.log('test'); as its contents.
By the way, in your posted code, you are loading jQuery using jQuery's own function. For this jQuery must already be loaded. It seems that you need to rethink how you are loading your scripts.
Why do you using ajax calls?
Did you know, Meteor merges head Tags of all html files. So you can make as example a 'scripts.html' File with content:
<head>
<script src=...
</head>

How to (ajax) post and execute response?

we have the following situation:
in default.aspx we have a link:
test.
and the JS code:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
if(data.indexOf("http://")==0)
window.open(data);
else{
var win=window.open();
with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close();
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The callback can first be an url address or 2nd html code that must be executed.
Option 1 fits, but in option 2, a new window will be opened where the code has been written but not executed.
It's clear, since it happens in the stream, it can't be executed. So the question, how can you fix it? Maybe a refresh(), or similar?
Because of the requirement of the customer, the workflow can not be changed, so it must be solved within doPost().
EDIT
The response in case 2 is HTML like this. This part should be executed:
<HTML><HEAD>
<SCRIPT type=text/javascript src="http://code.jquery.com/jquery-latest.js">
</SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready(function() {
do_something...
});
</SCRIPT>
</HEAD>
<BODY>
<FORM>...</FORM>
</BODY>
</HTML>
Please help. Thanks.
In your JS code it should be something like this:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
//if(data.indexOf("http://")==0)
if (data.type!="url") //i will add a data type to my returned json so i can differentiate if its url or html to show on page.
window.open(); // I dont know why this is there. You should
else{
var win=window.open(data.url); //This data.url should spit out the whole page you want in new window. If its external it would be fine. if its internal maybe you can have an Action on one of your controllers that spit it with head body js css etc.
/* with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close(); */ // No need to write data to new window when its all html to be rendered by browser. Why is this a requirement.
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The overall logic is this
You do your ajax call on doPost
Find out if data returned is of type url or anything that need to open in new window
If it is url type it would have a url (check if this is not null or empty or even a valid url) then open a new window with that url. Have a read of W3C window.open for parameters
If you want to open and close it for some reason just do that by keeping the window handle but you can do this on dom ready event of that new window otherwise you might end up closing it before its dom is completely loaded. (someone else might have better way)
If its not url type then you do your usual stuff on this page.
If this does not make sense lets discuss.

Categories