A JavaScript script only works on Internet Explor

2019-04-03 11:29发布

问题:

I got a script working on Firefox 5 but not with Internet Explorer 9. When I just open the Internet Explorer Developer Toolbar addon and try the same actions as before - it works. There is other JavaScript code on the page which is working, so it is just a part that isn't.

Is there something like the developer toolbar changing any options of Internet Explorer while running?

回答1:

Without your having quoted any code, one has to guess.

My guess is that you're using console.log (or one of the other console methods) in your code. On IE8 and IE9, the console object doesn't exist until/unless the developer tools are open. Strange but true.

You should be getting script errors along the lines of "console is undefined" when you don't have the dev tools open.

Because of this, and because console doesn't exist in every browser (certainly not IE6 or IE7, which still combined make up about 18% of the general browsing users), it's best not to include them in production code or to check proactively that console exists before using it.



回答2:

Is your script accessing or running any methods that are only available when the developer toolbar is open, such as console.log? For example, running console.log when console is undefined because the developer toolbar isn't open will cause an exception to be thrown.



回答3:

As mentioned in a similar question, use this code (in a script tag at the top of your page before other script tags, preferably):

(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

or find a more up to date version of this same code here: https://github.com/h5bp/html5-boilerplate/blob/master/src/js/plugins.js

This just solved that same issue for me.