How do I resolve Jquery.load() deprecated warning [duplicate] - javascript

I'm getting a warning message:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
when performing an asynchronous AJAX request that contains a script (that has local src), which is injected into HTML, using $.html() method. I've changed the given script to contain async="async", yet the warning message still remains.
I've started debugging the issue to discover that my appended <script> is handled via jquery AJAX call from jQuery.ajaxTransport (http://code.jquery.com/jquery-1.10.0.js, #8663), where async is set to false (that's probably where the issue comes from).
Now - what can I do about this?
The message appears in newest version of Chrome as well as Firefox.
While I cannot provide a test case on jsfiddle, here's a test case that displays the issue:
test.html
<html>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: '/response.html',
success: function(response){
$(document.body).html(response);
}
})
});
</script>
</body>
</html>
response.html
<script type="text/javascript" src="/json.js" async="async"></script>
json.js
console.log('hi');
AJAX request is not necessary to trigger the warning - all is needed is inserting a <script>
test2.html
<html>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script>
$(document).ready(function(){
$(document.body).html('<script type="text/javascript" src="/json.js" async="async"><\/script>');
});
</script>
</body>
</html>
It's worth noting that this has been fixed, per https://github.com/jquery/jquery/issues/2060

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use
following snippet BUT be aware that now you will lose sync behaviour of
script loading in the targeted content.
You could fix it, setting explicitly async option of xhr request to true:
$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
options.async = true;
});

Browsers now warn for the use of synchronous XHR. MDN says this was implemented recently:
Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request
Here's how the change got implemented in Firefox and Chromium:
https://bugzilla.mozilla.org/show_bug.cgi?id=969671
http://src.chromium.org/viewvc/blink?view=revision&revision=184788
As for Chrome people report this started happening somewhere around version 39. I'm not sure how to link a revision/changeset to a particular version of Chrome.
Yes, it happens when jQuery appends markup to the page including script tags that load external js files. You can reproduce it with something like this:
$('body').append('<script src="foo.js"></script>');
I guess jQuery will fix this in some future version. Until then we can either ignore it or use A. Wolff's suggestion above.

Even the latest jQuery has that line, so you have these options:
Change the source of jQuery yourself - but maybe there is a good reason for its usage
Live with the warning, please note that this option is deprecated and not obsolete.
Change your code, so it does not use this function
I think number 2 is the most sensible course of action in this case.
By the way if you haven't already tried, try this out: $.ajaxSetup({async:true});, but I don't think it will work.

I was plagued by this error message despite using async: true. It turns out the actual problem was using the success method. I changed this to done and warning is gone.
success: function(response) { ... }
replaced with:
done: function(response) { ... }

if you just need to load script dont do as bellow
$(document.body).html('<script type="text/javascript" src="/json.js" async="async"><\/script>');
Try this
var scriptEl = document.createElement('SCRIPT');
scriptEl.src = "/module/script/form?_t="+(new Date()).getTime();
//$('#holder').append(scriptEl) // <--- create warning
document.body.appendChild(scriptEl);

In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.
According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.
You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com

In my case if i append script tag like this :
var script = document.createElement('script');
script.src = 'url/test.js';
$('head').append($(script));
i get that warning but if i append script tag to head first then change src warning gone !
var script = document.createElement('script');
$('head').append($(script));
script.src = 'url/test.js';
works fine!!

Related

Why does jQuery's ajax automatically run scripts?

I noticed recently that if jQuery ajax is called right after injecting jQuery into an inner iframe, jQuery loses its functions - like jQuery(..).dialog(), .draggable, and any other plugins. If the ajax call is commented out, the jQuery works fine. Is this a known bug, or something I'm doing wrong? This problem can be seen in this file, with jQuery in the same directory:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="jquery.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
Try and <button id="btn">load</button>
<iframe width=300 height=300></iframe>
<script>
"use strict";
jQuery('#btn').click(function(){
var $ = jQuery;
console.log(typeof jQuery('iframe').dialog);
var doc = jQuery('iframe')[0].contentDocument;
function insertscript(src) {
var newscript = doc.createElement('script');
newscript.setAttribute('src',src);
doc.documentElement.appendChild(newscript);
}
insertscript('jquery.js');
//This breaks the jQuery plugins:
var test = $.get('jquery.js',function(){
//Now we know jQuery should be in the frame.
});
//So does this:
//jQuery.ajax({url:'http://192.168.1.17/wordpress/wp-includes/js/jquery/jquery.js',cache:true,processData:false});
console.log(typeof jQuery('iframe').dialog);
window.setTimeout(function(){
//jQuery is no longer the original jQuery object. Note the cached reference $().dialog does exist though.
console.log('after awhile... dialog is ' + typeof jQuery('iframe').dialog);
},3000)
//jQuery.ajax({url:jqurl,cache:true,processData:false});
});
</script>
</body></html>
This is a minimal sample of the problem, making sure the iframe has loaded a certain jQuery.js (then ajax should have the cached script) before some other stuff is added to the iframe.
Click load, and after while, console log will show "after awhile... dialog is undefined" - only when ajax was used.
Update: It looks like $.get('jquery.js') actually runs the script. $.get('alert.js') shows an alert, when alert.js has an alert function. (In the case of jQuery, re-defining the global jQuery reference.) Why does jQuery's ajax have this behavior? Does this happen with all ajax implementations?
As someone answered earlier (whose answer got deleted?), jQuery ajax automatically chooses what to do depending on what type of content you requested. (An unfortunately under-documented feature). loading an external js will not just return when the browser has fetched the script, it will also run the script.
Whenever you re-include jQuery at a later point, it rewrites the window.jQuery object, therefore removing the jQuery.prototype.dialog, etc.
The Firefox .watch function can be helpful in cases like this, to see where something got redefined. This, for example, would give you a stack trace of anything that redefines jQuery:
window.watch('jQuery',function() { console.trace() } )

How to load an external JS library that has code between <script> tags using jQuery

The original code I have is
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: qwerty
</script>
I want to make this code happen using jQuery after something has been triggered. Something like this
jQuery.getScript('http://platform.linkedin.com/in.js');
The problem is that I am not sure what the api_key part does, I've never seen the combination of a request to external lib and code between script tags. Is there a way to imitate that with jQuery? And also - what does that line do? :)
Thanks!
It's not exactly the answer to the question I originally posted, which is more abstract. But in case someone stumbles on this question in connection to linkedin, here's the way to load their framework asynchronously.
jQuery.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
IN.init({
api_key: "qwerty"
});
});
I did some digging through what happens when you load the script, and found that in.js parses the contents of the tag whose src is itself and uses them to build a new script tag to append to the head.
Based on your post, it appended
<script src="https://www.linkedin.com/uas/js/userspace?v=0.0.2000-RC1.20888-1402&apiKey=qwerty&"></script>
to the head. userspace.js obviously rejected the api key, but because this is a proprietary method of loading data, I can't predict how it'll work if and when you try to turn that into an ajax call.
Update:
According to the script tag standard, "If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI." This allows LinkedIn to get away with putting invalid Javascript inside the script tag, knowing it'll never get evaluated by the browser.
This should work correctly on jQuery mobile site.
<script type="IN/Apply" data-companyname="XXX" data-jobtitle="XXX" data-joblocation="XXX" data-email="XXX#XXX.XXX">
</script>
<script type="text/javascript">
$(function() {
if(typeof(IN)=="undefined"){
$.getScript("//platform.linkedin.com/in.js?async=true", function success() {
IN.init({api_key: "XXX"});
});
}
else{
IN.parse();
}
});
</script>

Javascript Errors: "No relay set", only in IE 7, 8

My javascript won't load because of errors it receives, only in IE. I used debugger to get the following errors. This page renders the javascript correctly in Safari, FF and chrome but not in IE and only on specific pages like this.
http://tsqja.deznp.servertrust.com/Lakeside_721_2_Shelf_Heavy_Duty_Utility_Cart_p/lak-721.htm
1) No relay set (used as window.postMessage targetOrigin), cannot send cross-domain message
2) Invalid argument. jquery.min.js
Any ideas what the first error implies? I have switched out my jQuery build with the latest and it still does the same thing.
UPDATE I have updated my jquery.min.js to the latest and it I figured out this is where the page stops loading...after the invalid argument pops up in the jquery-latest.min.js, line 16 character 15511 which is the following letter 'b':
finally{b=[e,f],c=0}}return this}
DEMO https://so.lucafilosofi.com/javascript-errors-no-relay-set-only-in-ie-7-8/
1) - No relay set (used as window.postMessage targetOrigin), cannot send cross-domain message
is caused by the <g:plusone /> button on your site: ( google is busy of this notice )
the only way i found to circumnvent this issue is by doing something like this:
$(function() {
setTimeout(function() {
gapi.plusone.render("plusone-div");
},
1500);
});
2) - Invalid argument. jquery.min.js
looking into your source-code is a chaos! ;-) OMG
you have lot's of errors like ( missing http:// protocol specified ):
different folder case-name like /v/newsite/ and /v/Newsite/ this really matter if you are under nix but since you are using ASP...
code like this AttachEvent(window, 'load', store_init); while using jquery like jQuery(document).ready(function() {
multiple inclusion of the same file ( this file is included 3 times ) /a/j/product_details.js
massive use of $(function(){ & $(document).ready(function(){ & $(window).load(function(){ multiple times when just one needed;
js global's all around the page, at the top, in the middle and at the bottom, they should stay all on top IMHO...
different version of jquery loaded at same time like: jquery-1.4.4.min.js & jquery-1.6.2.js & 1.4.2/jquery.min.js together
minor but always crappy, you have <meta /> , <link /> and <script /> in mixed order just like a chicken salad, where they should stay in order meta, links and script preferably at the end of the page.
missing semi-colon ; all around;
non-sense/malformed code like below and much much more...
if (!/\/shoppingcart\.asp/i.test(window.location.pathname)) {
jQuery(document).ready(function() {
jQuery('a').each(AddCartLink)
});
}
var global_Config_EnableDisplayOptionProducts = 'False';
var global_ImageSeed = 'test.jpg';
global_ImageSeed = global_ImageSeed.substring(...
your site with no errors: https://so.lucafilosofi.com/javascript-errors-no-relay-set-only-in-ie-7-8/
what i have done is:
reordered main tags meta,links,script
removed shitty widgets like addthis, google, facebook
"tried" to place all the globals to the top;
commented the part of the code that cause chrome problems in the TopScriptsTEST5.js this file is your main problem, ( you should see an huge chunk of code commented )
removed duplicate file inclusion,
removed latest version of jquery, cause i strongly doubt that all the rest of your code work with the latest jquery version, so use the 1-4-4 instead
some other fix here and there... nothing special
hope this check-up help a little, but i think you need an exorcist ;-)

Script tags added via jQuery not visible in FireBug

I am adding <script type="text/javascript" src="http://somedomain/somescript.js"> to the document head via jQuery. This is the code I use:
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = (document.location.protocol == "https:" ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
$("head").append(s);
});
While the script seems to be working perfectly, I do not see the scripts in the head when I use FireBug to inspect document head. This snippet does not show the added script(s) either:
$('script[src]').each(function(){
console.log(this.src);
});
Is this normal or am I doing something wrong here? What bothers me is the fact that I see other scripts in the head section that were lazy/dynamically loaded but not those that I added. Also wondering if it is OK to load scripts that manipulate DOM in the document ready function.
UPDATE
Replacing the code from:
$("head").append(s);
to
document.getElementsByTagName("head")[0].appendChild(s);
fixes the problem. The resulting DOM appears correctly in FireBug and jQuery correctly returns the script tags that were added static/dynamically.
You will see a request being made to the script in the NET tab but the script tag won't be visible when inspecting the DOM. This seems like a bug in FireBug.
This is a bug in Mozilla's 'jsd' debugger support. One workaround is post on the on the bug cited above:
http://code.google.com/p/fbug/issues/detail?id=1774
If jquery used eval() instead of script tag injection then you could debug this in Firebug.
Ok, I found this tip on jQuery.com:
> It should be noted that any attempts to append script elements using this
> method will fail silently:
> $('#element').append("<script></script>");
>> Not exactly. Scripts will be evaluated first, and then discarded.
>> So, if you do this:
>> $('#element').append("<script>alert('hello');</script>");
>> You'll see the alert.
This probably means that the script is evaluated but not inserted in the DOM.
Test it in Chrome as well using the Right-click "Inspect Element" option to use the full debugger (view source will not show the script's modifications). The elements HTML tab should show real-time changes to the DOM

JavaScript TinyMCE/jQuery race condition on firefox

I have a website with a form that uses TinyMCE; independently, I use jQuery. When I load the form from staging server on Firefox 3 (MacOS X, Linux), TinyMCE doesn't finish loading. There is an error in Firefox console, saying that t.getBody() returned null. t.getBody(), as far as I understand from TinyMCE docs, is a function that returns document's body element to be inspected for some features. Problem doesn't occur when I use Safari, nor when I use Firefox with the same site running from localhost.
Original, failing JavaScript-related code looked like this:
<script type="text/javascript" src="http://static.alfa.foo.pl/json2.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.ui.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({ mode:"specific_textareas", editor_selector:"mce", theme:"simple", language:"pl" });
</script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.jeditable.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.tinymce.js"></script>
<script type="text/javascript" charset="utf-8" src="http://static.alfa.foo.pl/foo.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ });
</script>
I tried changing script loading order, moving tinyMCE.init() call to the <script/> tag containing $(document).ready() call—before, after, and inside this call. No result. When tinyMCE.init() was called from within $(document).ready() handler, the browser did hang on request—looks like it was too late to call the init function.
Then, after googling a bit about using TinyMCE together with jQuery, I changed tinyMCE.init() call to:
tinyMCE.init({ mode:"none", theme:"simple", language:"pl" });
and added following jQuery call to the $(document).ready() handler:
$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });
Still the same error. But, and here's where things start to look like real voodoo, when I added alert(i); before the tinyMCE.execCommand() call, alerts were given, and TinyMCE textareas were initialized correctly. I figured this can be a matter of delay introduced by waiting for user dismissing the alert, so I introduced a second of delay by changing the call, still within the $(document).ready() handler, to following:
setTimeout('$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });',1000);
With the timeout, TinyMCE textareas initialize correctly, but it's duct taping around the real problem. The problem looks like an evident race condition (especially when I consider that on the same browser, but when server is on localhost, problem doesn't occur). But isn't JavaScript execution single-threaded? Could anybody please enlighten me as to what's going on here, where is the actual problem, and what can I do to have it actually fixed?
The browser executes scripts in the order they're loaded, not written. Your immediate scripts -- tinyMCE.init(...) and $(document.ready(...)); -- can execute before the files finish loading.
So, the problem is probably network latency -- especially with 6 separate scripts (each requiring a different HTTP conversation between the browser and server). So, the browser is probably trying to execute tinyMCE.init() before tiny_mce.js has finished being parsed and tinyMCE is fully defined.
If don't have Firebug, get it. ;)
It has a Net tab that will show you how long it's taking all of your scripts to load.
While you may consider the setTimeout to be duct taping, it's actually a decent solution. Only problem I see is that it assumes 1 second will always fix. A fast connection and they could see the pause. A slow connection and it doesn't wait long enough -- you still get the error.
Alternatively, you might be able to use window.onload -- assuming jQuery isn't already using it. (Can anyone else verify?)
window.onload = function () {
tinyMCE.init(...);
$(document).ready(...);
};
Also, was that a direct copy?
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ }
</script>
It's missing the ) ending ready:
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ })
</script>
Missing punctuation can cause plenty of damage. The parser is just going to keep reading until it finds it -- messing up anything in between.
Since this is the first page which came in google when I asked myself the same question, this is what i found about this problem.
source
There's a callback function in tinyMCE which is fired when the component is loaded and ready. you can use it like this :
tinyMCE.init({
...
setup : function(ed) {
ed.onInit.add(function(ed) {
console.log('Editor is loaded: ' + ed.id);
});
}
});
If you are using jquery.tinymce.js then you don't need tiny_mce.js because TinyMCE will try to load it with an ajax request. If you are finding that window.tinymce (or simply tinymce) is undefined then this means that the ajax is not yet complete (which might explain why using setTimeout worked for you). This is the typical order of events:
Load jquery.js with a script tag (or google load).
Load TinyMCE's jQuery plugin, jquery.tinymce.js, with a script tag.
Document ready event fires; this is where you call .tinymce(settings) on your textareas. E.g.
$('textarea').tinymce({ script_url: '/tiny_mce/tiny_mce.js' })
Load tiny_mce.js this step is done for you by TinyMCE's jQuery plugin, but it could happen after the document ready event fires.
Sometimes you might really need to access window.tinymce, here's the safest way to do it:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
alert(tinymce);
}
});
TinyMCE will go so far as to create a tinymce.Editor object and execute the setup callback. None of the editor's events are triggered and the editor object created for the document is not added to tinymce.editors.
I also found that TinyMCE's ajax call was interfering with my .ajaxStop functions so I also used a setTimeout:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
setTimeout(function () {
$(document).ajaxStart(function(e) {/* stuff /});
$(document).ajaxStop(function(e) {/ stuff */});
}, 0);
}
});

Categories