Javascript not working when loaded async - javascript

I had the following code on my page:
<script src="https://chatserver.comm100.com/js/LiveChat.js?siteId=&planId=2594&partnerId=-1" type="text/javascript"></script>
This script takes forever to load and so I wanted to load it async, so it does it's own thing while the rest of the page is downloaded / rendred. So I put in this code:
(function() {
var s = document.createElement('script');
s.type = "text/javascript";
s.src = 'https://chatserver.comm100.com/js/LiveChat.js?siteId=&planId=2594&partnerId=-1';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s,x);
})();
But when I use the latter, the code does not run. It is a little hard to debug, since the file is minified.
Is there anything I am missing about the async loading? Any other steps I need to take?
Thank you!

async is a new HTML5 attribute for the script tag. You'll want to check browser support. When supported, you should not have to have your custom script at all; just write:
<script ... async="async"></script>

Related

Javascript: best way to wait for script loaded synchonously before executing function?

I have the following problem:
I load a page inside a modal dialog. This page uses jQuery as dependency. Since I already use jQuery on the main page, for me, it is always available. Now we have the usecase, that also different pages (hosted on different domains) need to load that page if necessary.
So, I check if the jQuery variable exists on this page and if yes, just go on with my code.
If it does not exist, on top of the template, I dynamically create a script element like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
And at the end of the template, I use a IIFE (to scope the jquery variable)
(function ($) {
.... code ....
})(jQuery);
However, since with this method, the script gets loaded asynchronously, sometimes I get the error: jQuery is undefined.
Now I came up by loading it synchronously, like this:
var xhrObj = new XMLHttpRequest();
// open and send a synchronous request
xhrObj.open('GET', "jquery.min.js", false);
xhrObj.send('');
// add the returned content to a newly created script tag
var se = document.createElement('script');
se.type = "text/javascript";
se.text = xhrObj.responseText;
document.getElementById('placeholder').appendChild(se);
This works fine, but the warning "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. to the end user's experience." made me think.
However, now I changed my code and just said
if (!window.jQuery) {
document.write('<scr' + 'ipt src="jquery.js"' + '>' + '</scr' + 'ipt>');
}
on top of my Template.
Dear javascript gurus, is this a reliable solution?
Use the onload attribute in async javascript
<script async src="siteScript.js" onload="window.MyInitialisation()"></script>
In javascript it would look like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.async = "async";
script.defer = "defer";
script.onload = function() {window.MyInitialisation()}
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

Adding a javascript line to a ruby site written in slim

I was given a javascript line that calls a javascript file which is made by a company called walkme.
I have an app/assets/javascript/application.js file that calls all of my jquery that I am using for the site. for example it contains:
require feed
which calls feed.js when someone is on the feed page. I would like the walkme.js to also be called at the same time this code is called
I am looking for a way to add this <script ... code to a ruby site that uses slim and jquery.
<script type="text/javascript">(function() {var walkme = document.createElement('script'); walkme.type = 'text/javascript'; walkme.async = true; walkme.src = 'https://cdn.walkme.com/thewalkme.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(walkme, s); window._walkmeConfig = {smartLoad:true}; })();</script>
I have tried a blunt style of just making a walkme.js in the same place as the feed.js and putting that <script ... code in that file while adding the necessary require walkme code, but that seems to do nothing.
Some info:
Ruby on Rails
Ruby 2.1.7p400
ubuntu 14.04 LTS server
some files are named *.html.slim
As you may be able to tell, I did not make all the ruby code and am not an expert in ruby, javascript or jquery.
If this was just an html site, I think could just add the line of code to the header.
Mostly, Javascripts are called after the page has finished loading, since you want to manipulate the DOM, most likely.
So, you either don't want to call the script in the head of your document, unless you have a document.ready in the script.
To answer your question then, if you want the following script:
function(){
var walkme = document.createElement('script');
walkme.type = 'text/javascript';
walkme.async = true;
walkme.src = 'https://cdn.walkme.com/thewalkme.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(walkme, s);
window._walkmeConfig = {smartLoad:true};
};
to be available only on the feed page of your application,
You can make this function a named function, in a separate file (say feed.js.coffee for example) and call the function in your slim view page as follow:
//feed.js.coffee:
#feed = ->
walkme = document.createElement('script')
walkme.type = 'text/javascript'
walkme.async = true
walkme.src = 'https://cdn.walkme.com/thewalkme.js'
s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore walkme, s
window._walkmeConfig = smartLoad: true
return
and in your view:
/feed.html.slim:
...
your codes...
...
coffeeview:
feed

Asynchronous PHP page loading within javascript tags

I have the following tag which loads a PHP and I need it to be loaded asynchronously thus everything in the containing page is load even if the called PHP file takes longer to return the value (or even is server is down).
<script language="JavaScript"
src="http://www.server.com/phpfile.php">
</script>
I've tried replacing it with the code use by FB and other methods for JS asynchronous loading but it does not work. The issue is that in this case it is a PHP file the one that is called, not a JS file.
I tried the following but it does not work when the called PHP script plugs HTML code (such as a div with an image) with document.write:
<script language="JavaScript">
(function () {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true; s.src = 'server.com/phpfile.php';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
</script>
Any ideas?
Thank you.

load multiple javascript file with using one javascript file

i want to load multiple javascript file using one javascript file
i have four javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="http://ec2-174-129-44-226.compute-1.amazonaws.com/apiTools/jquery.livequery.js"></script>
<script src="http://localhost/effbugs/apiTools/tools.js?apikey=fztxljpnxqtssgtiquwr&pid=1"></script>
i want to intergrate above four javascript in one javascript file that i will load one instead of four and i will work proper
please give me suggestion for that
please help me
thanks...
Well, there are a few options:
1. Combine them into one file
Here is how you can do it with cat:
cat jsfile1.js jsfile2.js jsfile3.js ... > combined.js
2. Load them via require.js
More info at requirejs.org.
3. Create an script element for each URL and append it to DOM
/**
* loader.js
*/
window.addEventListener('load', function () {
var head = document.getElementsByTagName('head')[0],
urls = ["http://code.jquery.com/jquery-1.10.1.min.js",
"http://code.jquery.com/jquery-migrate-1.2.1.min.js",
"http://ec2-174-129-44-226.compute-1.amazonaws.com/apiTools/jquery.livequery.js",
"http://localhost/effbugs/apiTools/tools.js?apikey=fztxljpnxqtssgtiquwr&pid=1"];
urls.forEach(function (url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
});
});
You can do in this way to include all js files, But while loading I guess they loads asynchronously and they might not maintain order the order.
var scriptElement = document.createElement('script');
scriptElement.src = 'http://code.jquery.com/jquery-1.10.1.min.js';
document.getElementsByTagName("head")[0].appendChild(scriptElement);
Its quite simple, you just copy the content of all 4 files and place them into 1 file in order like this.
Master.js:
// Content of jquery-1.10.1.min.js
// Content of jquery-migrate-1.2.1.min.js
// Content of jquery.livequery.js
// Content of tools.js
Or
Master.js:
var script = document.createElement('script');
script.src = 'jquery-1.10.1.min.js';
document.head.appendChild(script);
// Do this for each file

How can I run a fallback copy of jQuery after the DOM is loaded?

The following are the first lines of code in a <script> tag just above the closing body tag in my document (it specifies that a locally-served copy of jQuery is run in the event that Google's CDN fails):
if(!window.jQuery){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/jquery.js';
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
jQuery(document).ready(function($){
// page behaviors
});
It does execute successfully, in the sense that if my computer is not connected to the Internet (this is a locally-served page), the local copy of jQuery is inserted. However, the document.ready() section below does not execute. I'm guessing this is because it is invoked before the fallback copy of jQuery takes effect. What's the proper practice for somehow "delaying" its execution so that either copy of jQuery will work properly?
Consider using an existing script loader such as yepnope. There's an example of exactly what you're trying to do on the home page.
You need to be sure that the script you are appending to the dom has finished loading before calling jQuery. You can do this with the technique described here:
if(!window.jQuery){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/jquery.js';
script.onreadystatechange= function () {
if (this.readyState == 'complete') jQueryLoaded();
}
script.onload = jQueryLoaded;
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
function jQueryLoaded() { };
You can also fetch the jQuery contents as an Ajax request, create a script tag with those as the body of the script and append it. That would also work.
Try that
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.2.min.js"><\/script>')</script>
<script>
jQuery(document).ready(function($){
// page behaviors
});
</script>
This way the script tag will be loaded synchronously.
The question "of how do I cope with my CDN failing and load a file hosted on my server" seems to come up a few times lately.
Question I'd ask is whether adding yet more js is the way to achieve the resilience and what level of resilience do the js approaches really add e.g. if the CDN is down they'll be a quick failure but how well do these approaches if the CDN is slow to respond how well do these solutions cope?
An alternative way to approach this is treat it as an infrastructure problem...
Run a CDN based on a domain/sub-domain you own. Have automated monitoring on it's availability, when it fails switch the DNS over to a backup server (anycast may provide an alternative solution too)
A php solution would be something like this:
$google_jquery = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
$fp = #fsockopen($google_jquery, 'r');
if (!$fp)
{
echo '<script type="text/javascript" src="js/jquery.js"></script>';
}
else
{
echo '<script src="'.$google_jquery.'"></script>' }
}

Categories