17
Mar/09
0

JavaScript in innerHTML

In some scripts I need to load mixed HTML and JavaScript code via ajax and assign it to a parsed divs innerHTML. The JavaScript code is only executed by the Firefox (3.x). All other browsers I tested (IE7 and Opera 9.x) do not execute the JavaScript code. In most cases the JavaScript code is written directly in a simple <script> tag. In some cases the fetched code contains script tags which refer to new javascript files. I built some code to workaround this problem…

20
Jan/09
1

JavaScript: Load CSS files dynamically

JavaScript

I had problems to add some custom CSS file dynamically after the page has been rendered and sent to browser. In detail I have some HTML code (a template) in a dedicated file which is fetched via AJAX and should be added to a div-Container. The HTML may contain a <link> element which points to a custom css stylesheet.

It was no problem to to fetch the HTML code and append it to a div-Container by setting div.innerHTML = strCode;.

I tested my code in Firefox: No problem. After I finished coding I tested in Internet Explorer 6 and 7. Big Problem: The CSS file was requested by the browser but not recognized when rendering the HTML code. The CSS definitions were OK. I did not find out the exact reason but I got a workaround.

My JavaScript code knows the path to the HTML template file on the server. The CSS file is named like the template file excepting the file extension. So I am able to request the CSS file on the fly by manipulating DOM.

var sTemplateName = 'default';
 
// Load template css file
var oLink = document.createElement('link')
oLink.href = '/path/to/template/tmpl.'+sTemplateName+'.css';
oLink.rel = 'stylesheet';
oLink.type = 'text/css';
document.body.appendChild(oLink);
oLink = null;
 
// Request template code and proceed...

The CSS file is fetched by the JavaScript code now therefore I can remove the <link> tag without hesitation.

Filed under: Javascript
19
Jan/09
2

JavaScript: Memory leak detection

JavaScript

While developing the new JavaScript front-end for NagVis 1.4 I needed to to find some memory leaks in my JavaScript code. I was searching for some useful programs which analyze a running JavaScript in the browser an search for leaks in it. A lot of such memory leaks in JavaScript are browser specific. So you need a program which finds the browser specific leaks. But there are also general problems in JavaScript and DOM Interaction. It is hard to find and learn all the leak patterns out there in the different browser engines. If you like to try just search a bit – there are a lot of sites with more information about what and why something is leaking. I provide a small overview about tools which may support you by searching for memory leaks.

  • Microsoft JavaScript Memory Leak Detector
    This is an add on for Internet Explorer provided by Microsoft. I tried a lot to get this work properly but was not able to. So it was useless for me. Maybe you are more lucky than me…
  • Drip
    Drip is based on the Internet Explorer engine. You can open some website in drip, wait some time and then click “Show DOM leaks”. The page closes and Drip shows a list of objects which are still in memory. This tool only shows the result, not the reason for leaks. But it is handy for focus your search.
  • Firefox Addon: Leak Monitor 0.4.2
    The leak monitor is an open source extension for Firefox. It is primary meant to track memory leaks in Firefox extensions but it creates a pop up window when you leave some page with a leak. I could not find any leaks with it. It was useless for me on tracking leaks.
  • SoftwareVerification JavaScript Memory Validator
    This is a commercial application which uses the Firefox in background. The developers like to add support for Internet Explorer but according to them it is not possible at the moment.
    The JavaScript Memory Validator monitors the memory usage and number of calls of the functions and methods of your website. It has a very handy feature called “hot spots”. With this you can find some critical parts of your code where you should focus your search on. I tested the trial of this program, working around some bugs, I was very excited of this program. I was able to find and track down some leaks with it.

You know other tools to track down memory leaks in JavaScript? Please leave a comment…

Filed under: Javascript
14
Jan/09
0

JavaScript: Optimize your for loops to better performance

This is a quickie about some JavaScript code performance tuning. This hint is not limited to JavaScript because the loop handling is equal in many other languages like e.g. PHP. This will not give the ultimate performance boost to your scripts but save you some time in big scripts with many for loops.

You know the easy form of looping an array with the for loop using the length methodas limiter:

var arrTest = [1,2,3,4];
for (var i = 0; i < arrTest.length; i++) {
  document.write(i+": "+arrTest[i]);
}

The big disadvantage of the above example is the “arrTest.length” call in the for call. Why? The problem is that JavaScript checks the second part of the for loop on every iteration. This means the length method is called 4 times in the above example. In fact it is only necessary to call it once to get the size of the array cause it never changes.

My favorite, and the smartest I know, way is to code it as follows:

var arrTest = [1,2,3,4];
for (var i = 0, len = arrTest.length; i < len; i++) {
  document.write(i+": "+arrTest[i]);
}

The speed difference is not really noticeable in this example. Run both loops a thousand times and you will see the results.

Filed under: Javascript
14
Jan/09
1

Don’t use “name” as global javascript variable! (IE Bug)

IE Bug Yesterday I spent several hours tracking a problem with the Nagios GUI in connection with a NagVis map in Internet Explorer. The problem occurred when opening a NagVis map in the default Nagios frame set. After loading the map all links in the sidebar were opening in a new window in Internet Explorer instead of the frame named “main”. More fun: When I had opened another page in a second tab which has a frame named “main”, the linked pages from the Nagios sidebar open in the frame of the second tab.

I was searching a lot to get a lead to the problem. First I thought about some invalid HTML code – that was all fine. After that I thought the problem was caused by a wrong doctype in the Nagios frameset. . Then I used the DOM Inspector for Internet Explorer to inspect the DOM tree in IE. There I recognized the frame named “main” was renamed right after loading the page. And it did not happen when there were no objects on the NagVis maps. So it was clear to me: The problem was that something changed the name of the frame and this happened somewhere in the new JavaScript object parsing code of NagVis.

Finally I found the problematic code and solved it in current NagVis code. Now read more about how to reproduce that problem by a simple example.

21
Apr/08
5

Firefox: Enable custom javascript context-menus

I want to replace or disable the browsers context menu on some pages. This task is not as easy as it sounds. There are some cross-browser issues with e.g. opera and safari. In the mentioned case this is no problem for me: Support for Firefox and Internet Explorer is enough.

But even full firefox support is not easy to realise. I had a problem with a firefox installation on ubuntu gutsy. When I called the contextmenu by doing a right-click on the page the default browser context menu opened (The custom context menu was covered by the default context menu). I knew the javascript code was correct cause it worked with some IEs, with the Firefox on a Windows system and also with the Firefox on another Linux system. So what’s the problem?

Firefox has an option which can be set by the user to prevent overriding the context menu by javascript. You can change the option as follows:

This option can be changed by calling about:config in the address bar and setting the option dom.event.contextmenu.enabled to True.

The option can even be changed through the Firefox GUI: “Tools > Options > Content > Advanced > Disable or replace context menus”.

Hope this saves someones time…

Filed under: Javascript
10
May/07
0

JS: overlib.js error “Unexpected call to method or property access”

Seit gestern hatte ich Probleme auf einer HTML-Seite, auf der ich Javascript Hover-Menus mit der Overlib verwende. Der Fehler war erstmalig aufgetreten, nachdem ich den folgenden Code in den Header eingefügt hatte.

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

Der Fehler trat nur im Internet Explorer auf, deswegen habe ich ihn auch nicht sofort entdeckt. Nachdem ich die Ursache des Fehlers gefunden hatte, ging es an die Fehlersuche. In der overlib.js (ich verwende nicht die aktuellste Version – aber auch mit dieser Version trat der Fehler auf) war der Fehler in Zeile 622 in der eingesetzten, in der neuesten Overlib-Version in Zeile 626 zu finden.

Die Fehlermeldung lautete im Internet-Explorer wie folgt: “Unerwarteter Aufruf oder Zugriff” (engl. unexpected call to method or property access).

Interessant ist noch, dass der Fehler beim erstmaligen Laden der Seite nicht aufgetreten ist, erst als die Seite durch ein

<META http-equiv="refresh" CONTENT="10;">

neu geladen wurde, meldete der Browser den Fehler. Dieses Verhalten kann ich mir immer noch nicht erklären.

Nun zur Lösung des Problems:

<script>

und

<style>

Tags erst am Ende des Headers einbinden.

Bei mir sah der Header in etwa wie folgt aus:

<head>
  <script type="text/javascript" src="./includes/js/overlib.js"></script>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <meta http-equiv="refresh" content="10;">
</head>

Mit diesem Header trat der Fehler auf. Nachdem ich den Header wie folgt umgestellt hatte, war der Fehler beseitigt:

<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <meta http-equiv="refresh" content="10;">
  <script type="text/javascript" src="./includes/js/overlib.js"></script>
</head>

Wieder was gelernt. Vielleicht hilfts noch jemandem weiter…

Filed under: Javascript
7
May/07
1

VBS/JS: Für die Dateierweiterung “*.js” gibt es kein Scriptmodul

Ich habe gerade den MGE Enterprise Power Manager zur Verwaltung von MGE USVs auf einem Deutschen Windows 2003 Server installiert. Während der Installation bzw. automatischen Konfiguration bekam ich folgende Fehlermeldung vom Windows Scripting Host: Für die Dateierweiterung “*.js” gibt es kein Scriptmodul.

Scheinbar kann WSH die JS Datei, die nach der Installation für die Konfiguration der Software zuständig ist (C:\Programme\MGE\EnterprisePowerManager\install\install.js), nicht ausführen bzw. beim Ausführen der JS-Datei wird die wscript.exe nicht aufgerufen. Der Dateityp JS war bei mir mit der Option “open” mit Ultraedit verknüpft (Hier zu prüfen: Explorer > Extras > Ordneroptionen > Dateitypen). Erstmal schein dabei nicht OK, dass dieser Vorgang auf einem Deutschen Windows eigendlich “Ö&ffnen” heißen müsste. Die Aktion sollte dann C:\WINDOWS\System32\WScript.exe “%1″ %* heißen.

Das gerade Biegen dieser Option hat das Problem bei mir allerdings nicht behoben. Daraufhin habe ich WSH per %windir%\inf\wsh.inf neu installiert. Nachdem ich das durchgeführt habe und die Installation von MGE Enterprise Power Manager nochmals durchgeführt hatte, lief diese ohne Fehlermeldungen durch.

Filed under: Javascript
25
Apr/07
4

Google Analytics: Firefox JS Error: “urchinTracker is not defined”

Ich habe mir testweise mal Google Analytics in das Blog eingebaut, auf einmal wirft mir mein Firefox folgenden Fehler:

Fehler: urchinTracker is not defined

Hier der Code, den man laut Google einbinden soll:

<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript">
_uacct = "UA-<ID>";
  urchinTracker();
</script>

Nachdem ich dann ein Wenig gesucht habe, habe ich folgenden Workaround gefunden, um die Fehlermeldung erstmal zu unterbinden:

<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript">
_uacct = "UA-<ID>";
if (typeof(urchinTracker) == 'function') {
  urchinTracker();
}
</script>

Der Code prüft vor dem Aufruf der JS Funktion, ob diese tatsächlich definiert ist.

Jetzt ist aber immer noch die Frage: Warum entsteht der Fehler? Die Antwort ist recht simpel: Das Firefox-Addon Adblock-Plus hat die URL http://www.google-analytics.com/* per Default in der Filter liste, also wird das JS-Script urchin.js von dort nicht geladen.

Simpel, aber da muss man erstmal hinter kommen – hat ein paar Minuten gedauert ;-).

Filed under: Javascript