Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a script only in IE

I need a particular script to be triggered in Internet Explorer browsers Only!

I've tried this:

<!--[if IE]>  <script></script> <![endif]--> 

Unfortunately this actually stops the script from being loaded.

EDIT: For everyone asking why I need this: IE makes scrolling extremely jumpy when using some animations. In order to address this I need to implement a script that provides smooth scrolling to IE. I don't want to apply it to other browsers as they don't need it and this script although making the scrolling smoother also makes it a bit unnatural.

like image 912
David Martins Avatar asked May 01 '15 13:05

David Martins


People also ask

How do I run an Internet Explorer script?

Internet ExplorerClick Tools > Internet Options. Click the Security tab > Custom Level. In the Scripting section, click Enable for Active Scripting. In the dialog box that displays, click Yes.

How do I add a script to my browser?

On the web browser menu click on the "Edit" and select "Preferences". In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox. Click on the "Reload the current page" button of the web browser to refresh the page.

How do you load a script in JavaScript?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.


1 Answers

I'm curious why you specifically need to target IE browsers, but the following code should work if that really is what you need to do:

<script type="text/javascript">     if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))         document.write('<script src="somescript.js"><\/script>'); </script> 

The first half of the Regex (MSIE \d) is for detecting Internet Explorer 10 and below. The second half is for detecting IE11 (Trident.*rv:).

If the browser's user agent string matches that pattern, it will append somescript.js to the page.

like image 91
nderscore Avatar answered Sep 23 '22 16:09

nderscore