I load my content using ajax, says it's content.html. So in content.html there's a script tag. I found a problem with this approach. I do a console.log('debug') within content.html, and load it with ajax, and it trigger every time. How to do a flag to prevent that?
Note that I can't load the js of content.html in global scope dude to some plugin conflicts.
It's only an idea... since we didn't see anycode yet...
And I'm still not sure what the problem really is.
If you want to leave this script in content.hmtl but disable it when called by layout.html.
You could do something like this in layout.html:
$("script").each(function(){
if($(this).attr("src")=="[particular source]"){
$(this).remove();
}
});
Or use an id if there is no src attribute.
This has to run after you got the ajax result....
I faced with the same issue.
Chrome load the js many times with unique VM files and execute all of them when the html in ajax is loaded.
Related
I have an issue loading a form in a bootstrap modal. I am using a service called Formstack to embed a form into my website. The embed code provided to me uses an external script to load the proper CSS, HTML, and JS into my page. The problem is that I am getting 10K+ warnings in my browser console once the page is loaded. All the warnings are the same. Each warning reads:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
Here is a link to that javascript file: https://trustdale.formstack.com/forms/js.php/business_contact
Looking at the external javascript, EVERY line begins with document.write. I dont know if it matters, but I am loading the form in a bootstrap modal. Also note that the form loads totally fine... unless I'm missing something. How would I load my form without all the warnings?
I figured it out... I dont quite understand it yet, but I stumbled upon this https://github.com/krux/postscribe, which seems to make my code work. I created an empty div in my modal with an id of #formCode, then placed this section of code in my footer:
<script>
$( function(){
postscribe('#formCode', '<script src={!! $contact_form !!}><\/script>');
});
</script>
$contact_form only contains the value of my script "src" attribute.
Again, dont know how it works, just does. Maybe someone could elaborate
I'm using a version of jquery-ui-widget, 1.10.3, that works well with ajax-loaded page fragment#1 but triggers an error with page fragment#2 if fragment#2 was loaded after fragment#1.
This is strange because even if I try and override 1.10.3 with 1.8.21 when ajax-loading fragment#2 (yes I realize this is a bad hack), the code that uses the widget factory still tries to use 1.10.3 and so causes an error.
Note that this is not a problem during normal page load as 1.8.21 is outside of my ajax div id="ajax_content" and so is loaded every time.
How can I override 1.10.3 during ajax?
<html>
<div id="ajax_content">
Page fragment #1 content
<script src="jquery-ui-widget.1.10.3.js"></script>
</div
<script src="jquery-ui-widget.1.8.21.js"></script>
</html>
VS.
<html>
<div id="ajax_content">
Page fragment #2 content
<script src="jquery-ui-widget.1.8.21.js"></script>
//having this script here or not has no effect if 1.10.3 was already loaded
</div>
<script src="jquery-ui-widget.1.8.21.js"></script>
</html>
version of jquery-ui-widget won't have an effect. Rather the cause of your problem is that the script added to the innerHTML of your div id="ajax_content" will not execute.
A script added dynamically (which maybe received as a response of an ajax request or that dynamically added to the innerHTML using js or jQuery) doesn't execute. Also it is not recommended as per #Kevin B's comment. I worked around the same problem by either of the two solutions below:
Load entire script initially
Load a new page with the script in the head tag
You may disagree with the second solution here saying that the question was about the script received as a ajax response while I am suggesting you to rework your approach and use a separate page instead. This may not be appropriate to do in your scenario due to various reasons but if the only reason preventing you from doing so is that this will cause code duplication then you may explore using something like jsp:include.
I'm experiencing an issue (which I still need to fix) where my entire page does not load. It gets cut off in the middle of an element.
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
I was thinking of just putting <div id="end_of_page"></div> at the bottom of the page, and checking if that was rendered, if not, i'll know something went wrong and can reload to try again.
thanks!!
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
You can do that, yes. Put this in the head after including jQuery:
<script>
jQuery(function($) {
if (!$("#end_of_page")[0]) {
// Something went wrong, load again
location.reload();
}
});
</script>
You'll enter the body of the loop (and so, force a reload) if the end_of_page element doesn't exist as of when the jQuery ready event fires (which is meant to be when the page is done loading).
But: Better by far to figure out why your page is getting cut off half-way through and solve that. This sort of workaround is not a solution.
You can use
$(document).ready(function(){
// code here
});
that code will only run when the page has loaded. A convenient shorthand is:
$(function(){
// code here
});
assuming your jQuery object is $. To finish your requirement, you can have a variable that is set within the load function, then use a timer set at the start of the page to check for it. If it's not there, reload.
Personally, I think you should invest some time into figuring out why your pages only half-way (Firebug or the Chrome Inspector may help you do this, it might be a resource in your page that is causing it to hang, and since most HTTP requests are only made 2 at a time per hostname, it might be waiting for that to return before fetching the rest).
Might be a server-side issue OR some script or library is stealing your fish $ (AKA: 'Dollar').
I'll rather suggest you to debug your code instead of refreshing the page trying to fix issues.
Make sure your scripts are in the head of your document, and jQuery + your jQ functions right before the closing </body> tag wrapped in:
(function($){ /*your functions*/ })(jQuery);
I was wondering if there is a way to execute script within a ajax dynamically loaded content.
I've searched the web and this forum also an find a lot of answers, like
[Running scripts in an ajax-loaded page fragment
[1]: Running scripts in an ajax-loaded page fragment [1]
But none of this seems to work fine for me.
I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.
For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:
//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,
$ajax([..]) //THEN
.ajaxSuccess(function(){
// LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
$(".script_target").each(function()
{
//DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
//EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
//WILL FIRE A SCRIPT RELATED TO drop_down CASE.
});
});
I know this is an ugly solution but i didn't came up with nothing better than this.
Can you help to improve this method?
Maybe there's a way to let the browser fire script within the loaded page automatically?
PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.
Thanks in advance.
If I understand you correctly :
you use "load" to retrieve html content from the server, and you add it to the page.
later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
but, depending on the markup retrieved, you want to do something different in the ajax callback
So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?
Otherwise maybe something like this would work :
In the callback of the "$.load" function, use $.data() to attach more information to created dom object
In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?
Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.
Hoping this helps.
EDIT : After your comment, it might be related to the selector you use when calling $.load().
There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :
$('#b').load('article.html #target');
Could this be your issue ?
Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).
This way, "loading" a page would be something along the lines of :
$.load("url_of_a_page_markup.html", function () {
require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
TheJsModuleForThePage.doSomething();
});
});
If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.
Hoping this helps.
If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.
Have you considered a module loader like require.js or Lab.js?
There are many other people asking similar questions:
does anyone knows good ajax script loader
Where are scripts loaded after an ajax call?
getting jQuery scripts and content through ajax dynamically
dynamic script loader in JS
Edit: I think I misread your question. Will try and come up with a better answer. Sorry!
Best of luck to you!
I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).
$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});
To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
(function() {
$('#myButton') // My button element
.button() // Initialize it as a JQuery UI button object
.click(function (){ // Hook up the button click event
$('#correct')[0].play(); // to play a sound in an <audio> tag
});
});
</script>
</head>
<body>
This is my help file, this is my code. This is for reading, this is for fun.
<button id="myButton">Button Text</button>
</body>
</html>
The dialog would load and the HTML displayed, but the embedded script did not execute.
I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.
This:
<script>
(function() {
...
});
</script>
Became:
<script>
(function() {
...
})(); // Immediately invoke
</script>
Niceness.
Interesting problem here from some inherited code I recently looked at. I'm trying to add a compression module to a project. It is loading all the JS and CSS files, combining them, minifying them, and compressing them. I've tried a number of solutions, but all of them have one fatal problem.
I have some javascript that is being loaded via Page.ClientScript.RegisterClientScriptBlock in the PreRender of the MasterPage. The compression module is loading as a Script Tag link in the MasterPage, but when I run the page... the code from the PreRender is lopped on top and is giving me a '$ is undefined' error, telling me jQuery isn't loaded yet.
Furthermore, I can't seem to get past the same problem when it comes to inline javascript on content pages.
Any ideas as to what is causing this? Enlighten me as I have no clue.
If have done this before with RegisterStartupScript (instead of RegisterClientScriptBlock) and called the $(document).ready(function() from WITHIN that script.
If the script tag link that eventually expands out to jquery is not in the head, but in the body of the page, then $ will be undefined when the script block executes, unless it is included in the html before the opening <form /> tag in the rendered html, which I understand is where RegisterClientScriptBlock spits out its script (just after that opening tag).
If this is not the case, and the joined/minified script is in the head, then I'd use a browser debugger such as Firebug or IE Dev Tools to verify that the jquery script is being correctly included in your combined script.
I know this answer is late to the party, but try calling ClientScript.RegisterClientScriptBlock in your OnPreRenderComplete (rather than OnPreRender) handler. This inserts the code later in the page rendering process.
All your jQuery code should be written inside the DOM-ready function:
$(function() {
// your code here
});
indipendently from where you place it in the page, 'cause the jQuery() function isn't avalaible before.