reactjs - How to load jQuery in a React App in IE9? Error SCRIPT5009: '$' -
i appreciate advice on how load jquery in react app involves simple form. want achieve here add placeholder support react form inputs in ie9 (the lowest ie version supported app).
i use detect-browser check , retrieve browser version. if ie9, load jquery in head tag , insert placeholders inputs using well-known jquery script below.
the way load jquery now, error script5009: '$' obvious reasons. doing wrong here , how can fix this? have tried import $ 'jquery'; , removing script loads jquery head doesn't fix problem, still same error above.
here code:
import react 'react'; const browser = require('detect-browser'); class app extends react.component { constructor(props) { super(props); this.ieplaceholder = this.ieplaceholder.bind(this); } ieplaceholder() { if(browser.name === 'ie' && browser.version === '9.0.0') { const scriptjquery = document.createelement("script"); scriptjquery.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"; document.head.appendchild(scriptjquery); const placeholdersiescript = ` $(document).ready(function() { $('[placeholder]').focus(function() { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); input.removeclass('placeholder'); } }).blur(function() { var input = $(this); if (input.val() == '' || input.val() == input.attr('placeholder')) { input.addclass('placeholder'); input.val(input.attr('placeholder')); } }).blur(); }); ` const script = document.createelement("script"); script.type = "text/javascript"; script.innerhtml = placeholdersiescript; document.head.appendchild(script); } } componentwillmount() { this.ieplaceholder(); } render() { return ( <div> <h1>a title</h1> <form> <input id="myinput" type="text" placeholder="myplaceholder" /> </form> </div> ); } } export default app;
you simple const $ = require('jquery'); after installing jquery npm, run script rather trying inject you're doing.
another approach use webpack. in webpack config file, can add plugin using syntax:
plugins: [ new webpack.provideplugin({ $: 'jquery', jquery: 'jquery' }) ] that automatically replace $ references in code jquery, although it's shortcut avoid using const $ = require('jquery'); elsewhere in code.
Comments
Post a Comment