How to load a js file with javascript - asp.net

I want to get over a nasty problem that shows up yesterday during a demo to a client. We're using jquery, loading it from google api. But yesterday, our ISP begin to cause some problems, and didn't load jq.js properly.
So, what I really want is to load a local file from the server if google api has an extrange behaviour (not that it's going to happen often, but at least doing local demos we won't get harmed again).
I know that <script type="txt/javascript" src="googleapi"> somejs </script> executes somejs when file in src doesn't load, but don't know any way to get the file load there.
Thanks in advance

inside you can put the following lines:
var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);

Teaching granny to suck eggs possibly, but why not just use a local copy on the demo machine always?

Edit :
I was a bit jumpy. The solution given by peirix is correct. I'll just use his code, to not let the wrong solution pollute this area. You can do
var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);
to load javascript dynamically.
Even this is prone to race conditions, however, if there are scripts in your page that depend on this script. Use with care.
This presentation - Even Faster Websites - elaborates on more techniques to load external files through javascript.

This isn't directly answering your question, but JQuery's creator John Resig has an interesting blog post about executing the script tag contents when there is also a src attribute.

Related

Meteor: [Load Order] Make JavaScript file load after HTML file is loaded?

Load Order Issues
I am having trouble making Meteor load my JavaScript after my HTML file fully loads when I go to localhost:3000. The problem is that my JavaScript keeps loading before my HTML file, and makes the page look unloaded when I use stuff like alert(); or prompt();. I've tried a lot of solutions such as naming my JavaScript file as main.js and putting my HTML file in a deeper directory and using <script> tags. I have also read the documentation concerning this: http://docs.meteor.com/#/full/structuringyourapp Solutions I've tired based off the documentation such as putting files in client/lib , client/compatibility , and lib have proven to no avail. I also tired Meteor.startupand I placed the file for it in the client folder. (The code inside it):
Meteor.startup( function () {
$.get("client/lib/testproject.html")
$.getScript("client/testproject.js");
});
The above sort of solved my problem, but it loaded the JavaScript file two times. The first time was before the HTML loaded and the second time was after the HTML loaded. I don't know a way to prevent the first JS load from happening when using Meteor.startup, so any solutions for that are also appreciated.
The JavaScript file's code I am referring to is simple. (In it's entirety):
prompt("Hello World!");
myList = ["apples", "oranges", "bananas"];
myList.forEach(function(value, index) {
alert('I have ' + value + ' for dinner.');
});
Summary
To summarize my problem:
My Problem:
Go to localhost
JavaScript loads first
HTML loads second
What I Need:
Go to localhost
HTML loads first
JavaScript loads second
The Question: How can I make my JavaScript load only after when my HTML is loaded? And how can I restructure my folder, file-names, and/or code to make it behave as I want it to in this case?
Since the code posted is extremely simple to reproduce I kindly ask that you
run your own solution with a setup similar to what I have and not something that uses a million packages since that is unnecessary for my case, on Meteor, before responding to this.
I'm on Meteor 1.1.0.2
Here is a link to my folder structure with included HTML code along with filenames I used: http://i.imgur.com/24z6bXF.png
I think you missed a decisive information : you should wrap your Javascript code into a Template.yourTemplate.rendered=function () {} function.
That is the meteor way to ensure that your related html code is properly rendered first.
First of all, Meteor will always repackage your files and load them automatically in a specific order (Meteor structuring your app). First files in client/compatibility then client/lib and then the others JS files.
You should also rewrite your code so it does not get executed immediately at load time, like wrapping everything in a function. And then, you should call this code when the DOM is loaded, which does not necessarily mean in Meteor.startup but also in onRendered callbacks in your templates.

Upgrading to new asynchrous Google Analytics code - should you do it?

I had read somewhere and have now forgotten that upgrading to the new asynchronous code will not enable one to track actual clicks for downloading items when user stays on the same page and that for tracking that you need to use the old version of GA code.
My question is, is that still the case and does anyone have any other reasons for not upgrading to use the newer asynchronous tracking?
thanks
Hmm...are you sure the "old" version of GA automatically tracked downloads? AFAIK GA never automatically tracked download links, that you always had to attach GA code (like a _trackEvent call) to your links yourself. But in any case, it's pretty easy to do it yourself, so it's really not a big deal. Plus, you get lots of benefits upgrading, and one day it may not even be an option to stick with the old version...
If you have jQuery you can for example do this:
// file types you want to consider a download
var downloadFileTypes = ['pdf','doc','docx','mp4'];
$(document).ready(function() {
$('a').filter(function() {
var ext = $(this).attr('href').split('.').pop().toLowerCase();
return ( $.inArray(ext, downloadFileTypes )>-1 );
})
.click(function() {
_gaq.push(['_trackEvent', 'Downloads', $(this).attr('href')]);
});
});
If you do not have a framework like jQuery, you can still do this easy enough with .getElementsByTagName() and using regular loops and conditions instead of the jQuery conveniences like .filter and .inArray
edit: Some things to note about that example:
the jQuery code was an example to hook the GA code to standard links pointing to the file types you specify in downloadFiletypes. It will only apply to links that exist at the time the code is executed. If you have links that may be dynamically generated on the page later, consider looking into .on() instead of .click()
you will need to make tweaks to matching links you want to consider downloads if they do not point to regular files with extensions. For instance, some websites have a controller script that expects a parameter with an ID and it dynamically serves up a pdf or whatever..if your files are like this, you will have to alter the logic to look for that instead.

ckeditor load html code in the editor asp.net

I am trying to load html file in CKEditor in asp.net but for some reason I don't know how to put the html code from the code behind file.
CKEditor1.FilebrowserBrowseUrl = url;
CKEditor1.BasePath = url;
CKEditor1.Text = content;
none of that helped
Any advice? Thanks in advance, Laziale
I'm not sure which version you are using, but let's suppose that it's 3.x. I was playing around with the control and didn't find any possible way of doing this from code behind. However, I managed to make it work like this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fckInitialization", #"
window.onload = function () {
var oEditor = CKEDITOR.instances['" + txtPost.ClientID + #"'];
oEditor.insertHtml('<strong>This is a bold text.</strong>');
};
", true);
I tried it in IE 8 and the last version of Mozilla (I think it was 9) and it worked. I also tried the same thing, but instead of window.onload I used the jQuery $(document).ready() and it worked only in IE. The reason is that you have to wait for everything to load in order to use the functions from the CKEditor API. I played with Firebug and the insertHTML worked.
If you are using 2.x, you can see somewhere in Google the same approach, but with a different API. I just can't find the link right now.
Another problem will be here, as you may figure out, that if you want to initialize a long text, you will have to write everything in a script, which is not really nice.
Maybe a possible solution for you will be to convert the HTML to BBCode first and then just set the Text property. This, of course, depends on the way you use the control, because BBCode does not contain all possible tags, but you can always modify the bbcode plugin of CKEditor to meet your needs. And I tested it and it works.
PS. Probably you can do it with the JavaScript method and an AJAX call.
Hope this helps!
Assuming ckeditor is being initialized from a textarea field, you can simply populate the body of the textarea.

Why is my javascript function not found by the page it is embedded in?

I have a page that has a simple javascript in the header portion of the page:
<script type="text/javascript">
function doLogout() {
var conf = confirm("Really log out?");
if (conf === true) { //changed == to === for boolean comparison
$.post("logout.aspx");
}
}
</script>
It uses jQuery to do an AJAX post to my logout page. The only issue right now is that when I click on the link (logout) to fire this function, nothing happens. I checked FireBug's console, and it told me that the function is not defined. This has happened to me before, but I think I botched a bunch of code to fix it sometimes.
Does anyone know the proper way to fix this issue?
Edit
After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise! Hopefully this information will be useful for more people.
This can also occur if there is a syntax error earlier in your javascript code. Often this will just be interpreted as the function not existing (nor any function AFTER the error). Check the code above this code (if there is any) and this code for syntax errors.
A way to tell if the cache error is it is to open Firebug and view the Script source. If the page was cached, you won't see your code. If it loaded but has syntax errors, the code will show, though it won't "find" it.
Things to test:
1) Can you call this function from something else? Like add a <script> at the bottom of the page to call it?
2) Does the page validate? Sometimes I get screwy javascript errors if there is some busted HTML like a missing </b>
3) I've been starting to wrap my javascript in <![CDATA[ ]]> just incase I've got goofy chars in my javascript.
4) I assume you've tested this in other browsers and have the same behavior, right?
5) If you haven't installed it already, install the Web Developer firefox addon. It has a nifty toolbar menu that will disable the cache for you so everything reloads.
6) As weird as it sounds, I once hit a javascript issue that was because of how my text editor was saving UTF-8 files. I forget the details, but it was adding some byte-order-mark or something that upset the browser.
I've had this occur when the page had been cached and so it didn't load the new script in. So to fix it clear all private data from Firefox. Not sure if that helps but it sure happened to me a bunch.
Other ideas for you to test:
is the function defined in the DOM tab in FireBug?
if you call doLogout() from the FireBug console, what happens?
I assume this is not the only script on that page. Make sure that some later script is not modifying doLogout to something else
I had the same issue and tried all that's been suggested here without success.
The only way I fixed it was by discovering that in the <script src="jquery.js"> tag I was using in the head of the page I forgot to close it with its </script> causing the page to ignore all Javascript functions. So please check that your includes look like:
<script src="jquery.js"></script>
I hope that helps. Ross.
If you are using DevExpress controls these links may help you: How to register and execute a JavaScript downloaded to the client via a callback and How to register and execute a JavaScript downloaded to the client via a callback (standalone JS file) and Executing javascripts from user controls dynamically created through ASPxCallback panels
The issue might occur if you have NoScript. You should check and make sure it's not blocking said script.
I had this issue and discovered the problem was just a wrong case letter inside the name.
Call: filterCheckbox()
vs
function filterCheckBox() {}
problem: lowercase "box" vs uppercase "Box".
So check if the name is exactly the same.

External JS file in web user control?

In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control?
After little googling I got this. It works but is this the only way?
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "MyUniquekey", #"<script src=""myJsFile.js"" type=""text/javascript""></script>", false);
-- Zuhaib
You can also use
Page.ClientScript.RegisterClientScriptInclude("key", "path/to/script.js");
That's the way I always do it anyway
Yes this works too .. but why does all
the script gets dumped in the body and
not in the head??
There's a potential workaround for that here
That's kind of incorrect .. about needing the Javascript in the body.
A Javascript function would sit in the head unexecuted and not at all affected by the fact that elements are still to load.
Often there is a single call at the end of a page to start execution of scripts at the top.
(Other methods available)
The only reason that script gets dumped in the body, is because MS doesn't seem to give 2 hoots about JavaScript.
Shame, because forcing us all to use .NET proper, just makes the world full of sluggish pages that needlessly run back and forth to servers for the tiniest requirmenet.

Resources