Including JavaScript at runtime is not working in IE8 - javascript

The below piece of code was working in IE6 & IE7 and almost all versions of FF. It just don't work in IE8. It doesn't work in the sense once I added the script tag in to HTML->HEAD element I don't see the script being loaded in the browser(the alerts in the script doesn't show up). I see the tags have been inserted in the HTML-HEAD though.
var head = document getElementsByTagName('head')[0];
// Check if the script is already loaded.
if (head ){
var script = document.createElement('script');
script.type = 'text/javascript';
script.language = 'JavaScript';
script.src = '/Tolven/scripts/' + jsFileName;
head.appendChild(script);
}
Does anybody have this issue? Or any clues to resolve this?

If this script is in <head> tag than head does not exists when this script is parsed and executed. So, of cource if (head) is false.
Your are using JS framework -- so feel free to use it's tools. And also do not forget to include Your framework, before using it.
<!-- if your are using mootools -->
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
window.addEvent('domready', function() {
// Your code...
});
</script>
<!-- if your are using prototype -->
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
document.observe("dom:loaded", function() {
// Your code...
});
</script>

Consider using a library like RequireJS or LABjs that do the job of including scripts at runtime really well.

var head = document getElementsByTagName('head')[0];
should be
var head = document.getElementsByTagName('head')[0];
Script seems to work after this modification.

This is was actually working. There is was an error(it only happens in IE8) in one of the scripts that's inserted at runtime. Eventually it's not executing alerts in the pages loaded next. Thanks for your answers though.

Related

How to make the browser run JavaScript code injected by DOM manipulation?

I want to serve a little HTML snippet that other pages can include.
The HTML content would look something like this:
<div id="coolIncludable" style="display:none"> <!--be invisible until you are finished initializing -->
<div>Cool stuff here</div>
<div>More cool stuff and so on...</div>
</div>
<script src="http://somehwere/jquery.js"></script>
<script src="http://somewhere/something.js"></script>
<script>
$(function(){$('#coolIncludable').show();});//<- actually contained in a script file, just for illustration
</script>
I'm planning to use the method detailed here: https://www.w3schools.com/howto/howto_html_include.asp to do the actual including. Let's say the page looks something like this:
<html>
<head>
</head>
<body>
<H1>Content before snippet</H1>
<div id="registerWrapper" html-include="http://somehwere/snippet.html">
No content loaded
</div>
<H1>Content after snippet</H1>
<script type="text/javascript" src="http://somehwere/html-include.js"></script>
</body>
</html>
The HTML snippet gets loaded and embedded all right, but the JavaScript that comes with it never gets executed. Is there a way to embed content including scripts that makes sure they are executed?
I don't expect to control the embedding page, so I cannot rely on it having jQuery or anything else loaded. I therefore avoided using jQuery in the embedding function and restricted myself to plain JavaScript. Loading jQuery is one of the things the <script> tags at the end of the snippets would do.
Since you are using jQuery you can use it's built in load() method to do what you want
Something like:
HTML
<div class="include" data-include="page2.html"></div>
JS
$('.include').each(function(){
const $el = $(this), url = $el.data('include');
$el.load(url)
});
Then make sure the script tag for the new content is below that content.
Simple working demo
In retrospect, my mistake is glaringly obvious:
What does the line $(function(){$('#coolIncludable').show();});
do? does it execute $('#coolIncludable').show();? No it doesn't. It registers a callback to do so that gets triggered by the 'load' event, which already has fired, and won't fire again.
On the other hand, that's really a moot point because the code never even gets executed.
Here's what I learned about dynamic loading of javascript
Injecting script tags directly does not work
script tags injected by setting element.innerHtml do not get executed
<div id="snippet">
...
</div>
<!-- neither of these will be executed -->
<script type="text/javascript">alert("stuff");</script>
<script type="text/javascript" src="http://somewhere/script.js"></script>
Creating script tags dynamically does work
What does work is dynamic tag generation the way it is described in this article: JavaScript Madness: Dynamic Script Loading
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'helper.js';
head.appendChild(script);
//At this point (or soon after) the code in helper.js will be executed
You would do that in your loading script. My loading script looks something like this:
function importJsFiles(){
const scriptFiles = ["http://somewhere/jquery.js",
"http://somewhere/stuff.js",
"http://somewhere/bootstrapSnippet.js"];
for (let i = 0; i< scriptFiles.length; i++){
importJsFile(scriptFiles[i]);
}
}
function includeSnippet(){
//See https://www.w3schools.com/howto/howto_html_include.asp
//We still have to do it without jQuery,
//because at the time this executes the injected jquery.js
//hasn't run and we do not yet have jQuery available
}
importJsFiles();
//At this point, all script tags are created, but the scripts are NOT loaded yet
includeSnippet();
//At this point, the dom is in its final shape
bootstrapSnippet(); //<- This won't work, because the script tags injected by this code won't be evaluated until after this file/function/whatever returns
//bootstrapSnippet.js
function bootstrapSnippet(){
alert("Snippet JS running")
if (window.jQuery) {
alert("JQuery is avaliable"); //<- This will fire, because the new script
// tags are evaluated in order, and we put the
// jquery.js one before the bootstrapSnippet.js one
}
//So now we CAN do this:
$('#coolIncludable').show();
}
bootstrapSnippet();
There are many more interesting ideas and details in this post that I picked the link above from. I hope someday I'll find time to explore them all.

How do I link scripts externally and internally?

I have a website that I want to work online and offline. I want to decrease load time, so I minified the slow loading scripts. It didn't work enough. Locally, some of the scripts are taking 4-6 seconds to load.
I know that linking scripts externally speeds it up drastically. I have tried it and it works. But some of the users will not have internet access. Is there a way to link a group of scripts to an external site, and locally if they do not have internet access?
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="ui/jquery-ui.min.js" type="text/javascript"></script>
You can do something similar to this answer. Basically, the idea is that you attempt to load the Internet based script for jQuery. Afterward, you do a normal script where you check if jQuery === undefined. If it does, you want to load the local copy.
Basically, an example of what you want to do:
<script src="[jQueryURL]" type="text/javascript"></script>
<script src="[dataTablesURL]" type="text/javascript"></script>
<script src="[jQueryUIURL]" type="text/javascript"></script>
<script type="text/javascript">
if(jQuery === undefined) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "js/jquery-1.9.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
//repeat for other two scripts here
}
</script>
What will happen is that it will attempt to load the scripts in question, and afterward it will check if jQuery is defined. If it's not, that means the scripts didn't load, so you want to load the local versions and append them to your header.
Ensure that the script declares a global variable you can test for. Then generate a local script loading element if the external script fails to load (which you can determine by testing for that variable).
<script src="http://example.com/example.js"></script>
<script>
if !(window.Example) {
document.write('<script src="../scripts/example.js"><\/script>');
}
</script>
<script type="text/javascript">
if(navigator.onLine)
{
alert("Connected");
}
else
{
alert("Not Connected");
}
</script>
First Check if internet connection exist then load external file other wise load internal file

Can you automatically choose between two <script src=""> files?

So lets say you're implementing a website that uses jQuery HEAVILY. You could put some code like
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and import it from some repository. If you're developing it without internet you could download the source and store it somewhere locally, then access it with some script like
<script src="js/jquery-1.10.2.min.js"></script>
But is there a simple way to have both? Such as if you can reach the repository use that, but if you can't use the local copy.
Check for a variable in the first script. If it is not found, use document.write to create the second script tag. Here is an example for jQuery I found here:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="js/jquery-1.7.1.min.js"><\/script>')</script>
The fail-safe way of referencing scripts on a CDN is to link to the local copy only if the CDN has failed for any reason.
The way to do this is simply to check if anything within the script has executed. For jQuery this is simply checking whether jQuery exists:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
if (!window.jQuery) document.write('<script type="text/javascript" src="/path/to/jquery-ver.sion.min.js"><\/script>');
</script>
Personally I have never had a script fail due to a CDN being offline, however I have had periods of internet outage. With scripts set up with a proper fallback, I've been able to continue local development as the pages still work without needing to connect to a CDN.
You can add resources dynamically if required one is not available. for eg:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
if( typeof $ != "function")
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'js/jquery-1.10.2.min.js';
head.appendChild(script);
}
</script>
</head>
<body>
</body>
</html>
Though JQuery hosted on Google CDN should be safe enough, the codes below can be used as a fallback with requireJS.
requirejs.config({
enforceDefine: true,
paths: {
jquery: [
'//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
'js/jquery-ui.min.js'
]
}
});
require(['jquery'], function ($) {
});

Wait for jQuery to load

I'm trying to check if jQuery is loaded. If not, load it, then proceed to load external javascript files. The issue I'm having is one of the external files expects to have jQuery already loaded, so I get a 'jQuery not defined" error. Is there a way I can load jQuery using JavaScript, and as soon as it's done then continue?
if(!window.jQuery){
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
//load these scripts after jquery has been loaded
<script src="/some/other/js/file/that/requires/jquery"></script>
<script src="/some/other/js/file/that/requires/jquery"></script>
What I'd like to do is wait for this to completely load before continuing. I tried this but I got errors about exceeding call stack
Consider the technique tried and tested by HTML5Boilerplate instead:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
Note that <script src="//ajax.googleapis.com only works on an actual http: or https: server; if you're testing on a local filesystem, write <script src="http://ajax.googleapis.com instead.

How to add jQuery in JS file

I have some code specific to sorting tables. Since the code is common in most pages I want to make a JS file which will have the code and all the pages using it can reference it from there.
Problem is: How do I add jQuery, and table sorter plugin into that .js file?
I tried something like this:
document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');
but this seems to not work.
What is the best way to do this?
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.3.min.js'; // Check https://jquery.com/ for the current version
document.getElementsByTagName('head')[0].appendChild(script);
If you want to include jQuery code from another JS file, this should do the trick:
I had the following in my HTML file:
<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>
I created a separate my_jquery.js file with the following:
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
$(this).hide("slow");
});
});
You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.
// Anonymous "self-invoking" function
(function() {
var startingTime = new Date().getTime();
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 20);
}
};
// Start polling...
checkReady(function($) {
$(function() {
var endingTime = new Date().getTime();
var tookTime = endingTime - startingTime;
window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");
});
});
})();
Other Option : - You can also try Require.JS which is a JS module loader.
/* Adding the script tag to the head as suggested before */
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "http://code.jquery.com/jquery-2.2.1.min.js";
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = handler;
script.onload = handler;
// Fire the loading
head.appendChild(script);
function handler(){
console.log('jquery added :)');
}
In if you want to add reference to any js file, say, from your project, you may also add it directly using reference tag, in Visual Studio IDE this is handled automatically by dragging and dropping the external file from solution explorer to current file (This works for mark up files, .js & .css files too)
/// <reference path="jquery-2.0.3.js" />
Here is the solution, that I adopted as a combination of some proposed solutions in some other forums.
This way you can reference both css files and other js files in one js file, thus making change next time only in a single place. Please let me know if you have any concerns on it.
I have done following:
I have created a js with name jQueryIncluder.js
declared and executed following code in this file
function getVirtualDirectory() {
var vDir = document.location.pathname.split('/');
return '/' + vDir[1] + '/';
}
function include_jQueryFilesToPage() {
var siteAddress = location.protocol + '//' + document.location.hostname + getVirtualDirectory();
var jqCSSFilePath = siteAddress + 'includes/jQueryCSS/ehrgreen-theme/jquery-ui-1.8.2.custom.css';
var jqCoreFilePath = siteAddress + 'includes/jquery-1.4.1.min.js';
var jqUIFilePath = siteAddress + 'includes/jquery-ui-1.8.2.custom.min.js';
var head = document.getElementsByTagName('head')[0];
// jQuery CSS jnclude
var jqCSS = 'cssIDJQ'; // you could encode the css path itself to generate id.
if (!document.getElementById(jqCSS)) {
var link = document.createElement('link');
link.id = jqCSS;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = jqCSSFilePath;
link.media = 'all';
head.appendChild(link);
}
// Core jQuery include
var jqc = "coreFileRefIDJQ";
if (!document.getElementById(jqc))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqc + '" src="' + jqCoreFilePath + '"></scr' + 'ipt>');
// jQueryUI include
var jqUI = "uiFileRefIDJQ";
if (!document.getElementById(jqUI))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqUI + '" src="' + jqUIFilePath + '"></scr' + 'ipt>');
}
include_jQueryFilesToPage();
I referenced the above jQueryIncluder.js file in another js or xsl file of my .Net project as following:
<script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
I hope my effort is appreciated.
Thanks
it is not possible to import js file inside another js file
The way to use jquery inside js is
import the js in the html or whatever view page you are using inside which you are going to include the js file
view.html
<script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
<script src="<%=request.getContextPath()%>/js/default.js"></script>
default.js
$('document').ready(function() {
$('li#user').click(function() {
$(this).addClass('selectedEmp');
});
});
this will definitely work for you
The following answer was posted previously by another user, but provided no explanation so I decided to annotate what is happening.
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
Explanation
The problem is solved by creating a script element in JavaScript, and then setting the src attribute to the path of the jQuery file.
var jQueryScript = document.createElement('script');
Above we create the script element.
Next we set the src attribute to the path as explained before.
This can be set to
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
or
/your/path/to/jquery/file
In use:
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
Last, but not least, appending the new element to the document head:
document.head.appendChild(jQueryScript);
or body:
document.body.appendChild(jQueryScript);
In Use
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
setTimeout(function() {
// Add the rest of your code here, as we have to wait a moment before the document has jQuery as a part of it.
$("body").html("<h1>It Works!</h1>");
}, 1000);
Theres a plugin for jquery where you can just include the files you need into some other js file, here is the link for it http://tobiasz123.wordpress.com/2007/08/01/include-script-inclusion-jquery-plugin/.
Also this document.write line will write the script tags in the html not in your js file.
So I hope this could help you out, a little with your problem
The problem is you're using </script> within the script, which is ending the script tag. Try this:
document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></sc'+'ript>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></sc'+'ript>');
I believe what you want to do is still to incude this js file in you html dom, if so then this apporach will work.
Write your jquery code in your javascript file as you
would in your html dom
Include jquery framework before closing body tag
Include javascript file after including jqyery file
Example:
//js file
$(document).ready(function(){
alert("jquery in js file");
});
//html dom
<body>
<!--some divs content--->
<script src=/path/to/jquery.js ></script>
<script src=/path/to/js.js ></script>
</body>
If you frequently want to update your jquery file link to a new version file, across your site on many pages, at one go..
Create a javascript file (.js) and put in the below code, and map this javascript file to all the pages (instead of mapping jquery file directly on the page), so when the jquery file link is updated on this javascript file it will reflect across the site.
The below code is tested and it works good!
document.write('<');
document.write('script ');
document.write('src="');
//next line is the path to jquery file
document.write('/javascripts/jquery-1.4.1.js');
document.write('" type="text/javascript"></');
document.write('script');
document.write('>');
You can create a master page base without included js and jquery files. Put a content place holder in master page base in head section, then create a nested master page that inherits from this master page base. Now put your includes in a asp:content in nested master page, finally create a content page from this nested master page
Example:
//in master page base
<%# master language="C#" autoeventwireup="true" inherits="MasterPage" codebehind="MasterPage.master.cs" %>
<html>
<head id="Head1" runat="server">
<asp:ContentPlaceHolder runat="server" ID="cphChildHead">
<!-- Nested Master Page include Codes will sit Here -->
</asp:ContentPlaceHolder>
</head>
<body>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<!-- some code here -->
</body>
</html>
//in nested master page :
<%# master language="C#" masterpagefile="~/MasterPage.master" autoeventwireup="true"
codebehind="MasterPageLib.master.cs" inherits="sampleNameSpace" %>
<asp:Content ID="headcontent" ContentPlaceHolderID="cphChildHead" runat="server">
<!-- includes will set here a nested master page -->
<link href="../CSS/pwt-datepicker.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery-1.9.0.min.js" type="text/javascript"></script>
<!-- other includes ;) -->
</asp:Content>
<asp:Content ID="bodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ContentPlaceHolder ID="cphChildBody" runat="server" EnableViewState="true">
<!-- Content page code will sit Here -->
</asp:ContentPlaceHolder>
</asp:Content>
Dynamic adding jQuery, CSS from js file.
When we added onload function to body we can use jQuery to create page from js file.
init();
function init()
{
addJQuery();
addBodyAndOnLoadScript();
addCSS();
}
function addJQuery()
{
var head = document.getElementsByTagName( 'head' )[0];
var scriptjQuery = document.createElement( 'script' );
scriptjQuery.type = 'text/javascript';
scriptjQuery.id = 'jQuery'
scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
var script = document.getElementsByTagName( 'script' )[0];
head.insertBefore(scriptjQuery, script);
}
function addBodyAndOnLoadScript()
{
var body = document.createElement('body')
body.onload =
function()
{
onloadFunction();
};
}
function addCSS()
{
var head = document.getElementsByTagName( 'head' )[0];
var linkCss = document.createElement( 'link' );
linkCss.rel = 'stylesheet';
linkCss.href = 'E:/Temporary_files/temp_css.css';
head.appendChild( linkCss );
}
function onloadFunction()
{
var body = $( 'body' );
body.append('<strong>Hello world</strong>');
}
html
{
background-color: #f5f5dc;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temp Study HTML Page</title>
<script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>
</head>
<body></body>
</html>
If document.write('<\script ...') isn't working, try document.createElement('script')...
Other than that, you should be worried about the type of website you're making - do you really think its a good idea to include .js files from .js files?
just copy the code from the two files into your file at the top.
or use something like this http://code.google.com/p/minify/ to combine your files dynamically.
Josh
I find that the best way is to use this...
**<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>**
This is from the Codecademy 'Make an Interactive Website' project.
After lots of research, I solve this issue with hint from ofir_aghai answer about script load event.
Basically we need to use $ for jQuery code, but we can't use it till jQuery is loaded. I used document.createElement() to add a script for jQuery, but the issue is that it takes time to load while the next statement in JavaScript using $ fails. So, I used the below solution.
myscript.js is having code which uses jQuery
main.js is used to load both jquery.min.js and myscript.js files making sure that jQuery is loaded.
main.js code
window.load = loadJQueryFile();
var heads = document.getElementsByTagName('head');
function loadJQueryFile(){
var jqueryScript=document.createElement('script');
jqueryScript.setAttribute("type","text/javascript");
jqueryScript.setAttribute("src", "/js/jquery.min.js");
jqueryScript.onreadystatechange = handler;
jqueryScript.onload = handler;
heads[0].appendChild(jqueryScript);
}
function handler(){
var myScriptFile=document.createElement('script');
myScriptFile.setAttribute("type","text/javascript");
myScriptFile.setAttribute("src", "myscript.js");
heads[0].appendChild(myScriptFile);
}
This way it worked. Using loadJQueryFile() from myscript.js didn't work. It immediately goes to the next statement which uses $.
The latest answer is outdated, try this:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.1.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
Why are you using Javascript to write the script tags? Simply add the script tags to your head section. So your document will look something like this:
<html>
<head>
<!-- Whatever you want here -->
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script src="/javascripts/jquery.tablesorter.js" type="text/javascript"></script>
</head>
<body>
The contents of the page.
</body>
</html>

Categories