to head based on screen width", "text": "<p>i need something easy like this:</p>\n\n<pre class="prettyprint"><code><script type="text/javascript">\n<!--\n\nif (screen.width <= 699) {\ndocument.location = "mobile.html";\n}\n//-->\n</script>\n</code></pre>\n\n<p>but instead of a redirect i'd need <code><script src="js.js"></script></code> to be appended in <code><head></head></code></p>\n\n<p>is that possible?</p>", "answerCount": 1, "upvoteCount": 837, "dateCreated": "2022-11-29 01:20:07", "dateModified": "2022-12-06 05:16:27", "author": { "type": "Person", "name": "valerio0999" }, "acceptedAnswer": { "@type": "Answer", "text": "<p>See it in action: <kbd><strong>Short Demo</strong></kbd></p>\n\n<hr>\n<p>You can define a function, like this:</p>\n\n<pre class="prettyprint"><code>function appendScript(pathToScript) {\n var head = document.getElementsByTagName("head")[0];\n var js = document.createElement("script");\n js.type = "text/javascript";\n js.src = pathToScript;\n head.appendChild(js);\n}\n</code></pre>\n\n<p>And then call it with the appropriate argument (e.g. according to screen size), like this:</p>\n\n<pre class="prettyprint"><code>appendScript("path/to/file.js");\n</code></pre>\n\n<hr>\n<p>If you also need to remove a script from <code>head</code> (e.g. based on its 'src' attribute), you can define a function, like this:</p>\n\n<pre class="prettyprint"><code>function removeScript(pathToScript) {\n var head = document.getElementsByTagName("head")[0];\n var scripts = head.getElementsByTagName("script");\n for (var i = 0; i < scripts.length; i++) {\n var js = scripts[i];\n if (js.src == pathToScript) {\n head.removeChild(js);\n break;\n }\n }\n}\n</code></pre>\n\n<p>And then call it with the appropriate argument (e.g. according to screen size), like this:</p>\n\n<pre class="prettyprint"><code>removeScript("path/to/file.js");\n</code></pre>\n\n<hr>\n<p>Also, note that using <code>screen.width</code> returns the size of the user's screen (not the browser-window's width). </p>\n\n<p>If you need to get the window size you can use <code>$(window).width()</code> (using jQuery). \nIf you want a "jQuery-free" solution, take a look at <strong>this answer</strong> for cross-browser alternatives.</p>", "upvoteCount": 88, "url": "https://exchangetuts.com/appending-script-srcscript-to-head-based-on-screen-width-1641534483002606#answer-1669944007161187", "dateCreated": "2022-12-05 17:16:27", "dateModified": "2022-12-06 05:16:27", "author": { "type": "Person", "name": "gkalpak" } } } }