On a page i try to fill an empty <iframe id="myFrame"></iframe> with the HTML code of an ajax result. That works well, except script tags in the code are not being executet, so i have to readd them to the iframe's page:
$.post('page.php', function(code) {
$("#myFrame").contents().find("html").get(0).innerHTML = code;
$("#myFrame").contents().find("script").each(function() {
$old_script = $(this);
$frame = document.getElementById("myFrame");
$new_script = $frame.contentWindow.document.createElement("script");
$new_script.type = "text/javascript";
$new_script.src = $old_script.attr("src");
$old_script.remove();
$frame.contentWindow.document.head.appendChild($new_script);
});
});
That works basically, but the document seems to load the Javascript files in a different order. There are 3 js files to load: jquery.min.js, a jquery plugin and a main.js file to control the bahavior inside the iframe:
// main.js:
$(document).ready(function() {
alert("frame document loaded");
// call the jquery plugins etc...
});
The page alerts me "frame document loaded", but cannot execute the jquery plugins. Double-checked the script paths, but they're right. Seems that the jquery.min.js and main.js are loaded before the plugin files.
How could i achieve to load the javascript files one by one as specified originally in the code returned by the ajax request?
EDIT: Forgot to say that sometimes everything works well and the javascript seems to be loaded correctly. On reload it breaks again.
Related
I am trying to get a script from another website using jQuery then document.write it
here is my code
var url = "https://code.jquery.com/jquery-1.10.2.js";
var dam = $.getScript(url);
document.write(dam);
But this doesn't work!!
all what I get on the page is [object Object]
Can this be achieved without XHR?
jsfiddle
Don't use document.write, it does not do what you think it does. What it does not do is write some data at the end of the document. What it does instead, is pipe data into the current write stream. And if there is no write stream, it will make a new one, resetting the document's content. So calling document.write(dam) means you just wiped your document. document.write is a low level JS function from an earlier era of JavaScript, don't use it.
Instead, you want to use modern DOM manipulation functions, so in jQuery, that's stuff like:
$(document.head).append($("<script>").attr("src", url));
where
$("<script>")
builds a new script element,
$(...).attr("src", url)
sets the "src" attribute to what you need it to be, and:
$(document.head).append(...)
or
$(document.body).append(...)
to get the script loaded into your document. If it's a plain script with src attribute, it can basically go anywhere, and if it's a script with text content that should run, you can only make that happen through document.head.
Although if it's just a script you need to load in and run, you can use getScript, but then you don't need to do anything else, it's just:
var url = "https://code.jquery.com/jquery-1.10.2.js";
jQuery.getScript(url);
Done, jQuery will load the script and execute it. Nothing gets returned.
Of course, the code you're showing is loading jQuery, using jQuery, so that's kind of super-odd. If you just want to load jQuery on your page, obviously you just use HTML:
<!doctype html>
<html>
<head>
...
</head>
<body>
...
<script src="http://https://code.jquery.com/jquery-1.10.2.js"></script>
</body>
</html>
with the script load at the end so the script load doesn't block your page. And then finally: why on earth are we loading jQuery version 1.x instead of 2.x? (if you need to support IE8: that's not even supported by Microsoft anymore, so you probably don't need to).
And finally, if we don't want to load the script, but we really just want its content, as plain text, there's only a million answers on Stackoverflow already that tell you how to do that. With jQuery, that's:
$.get("http://https://code.jquery.com/jquery-1.10.2.js", function(data) {
$(document.body).append($("div").text(data));
});
But you knew that already because that's been asked countless times on Stackoverflow and you remembered to search the site as per the how to ask instructions before asking your question, right?
executing the script on the page is not my goal!. I want to get the
script content and put it a div (USING JAVASCRIPT - NO XHR) , is that
possible ?
Try utilizing an <iframe> element
<div>
<iframe width="500" height="250" src="https://code.jquery.com/jquery-1.10.2.js">
</iframe>
</div>
jsfiddle http://jsfiddle.net/snygv469/3/
Make it easier... use my fiddle
http://jsfiddle.net/wwwfzya7/1/
I used javascript to create an HTML element
var url = "https://code.jquery.com/jquery-1.10.2.js";
var script = document.createElement("SCRIPT"); //creates: <script></script>
script.src = url; //creates: <script src="long_jquery_url.js"></script>
document.body.appendChild(script); //adds the javascript-object/html-element to the page.!!!
Use this way, it can fix your problems.
$.get( "https://code.jquery.com/jquery-1.10.2.js", function( data ) {
alert(data);
});
You can try adding
<script src="http://code.jquery.com/jquery-1.8.3.min.js" ></script>
Then an AJAX call, but it pulls data from CACHE. It looks like an AJAX but when <script> is added file goes in cache, then read from cache in the ajax. In cases where it is not stored in cache read it using normal AJAX.
jQuery.cachedScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "text",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
$(document).on('ready', function() {
// Usage
$.cachedScript("http://code.jquery.com/jquery-1.8.3.min.js").done(function(script, textStatus) {
console.log(script);
});
});
Normal Solution
If you are ready to use AJAX look at this fiddle
How to fetch content of remote file and paste it on your document and execute that js code
I guess you want to get content written on remote file and want to write that content in your HTML. to do this you can use load() function.
To do this follow the following steps:
1. Create a file index.html Write the following code in it:
<pre id="remote_script"></pre>
<script>
$(document).ready(function() {
//var url = "https://code.jquery.com/jquery-1.10.2.js";
var url = "remote_script.html";/* For testing*/
$('#remote_script').load(url,function(){
eval($('#remote_script').text()); /* to execute the code pasted in #remote_script*/
});
});
</script>
2. Create another file remote_script.html for testing write alert('a'); in it without any <script> tag and run the above code.
I'm creating a Java Script widget for the site based on CodeIgniter. The site using templates and Blade library. I need to load my java script right after the page has been loaded. I have added it into template scripts.blade.php:
<script src="{{apps_url('assets/my_widget/js/my_widget.js')}}"></script>
Unfortunately, it seems, what my script was executed before controller has been loaded and therefore the script can not find required SVG object:
(function() {
var container = d3.select(".myContainer");
alert("container: " + container);
})();
This alert show what container is null even if the myContainer object actually exists on the page and was recognized by CSS. The d3 library has been loaded properly and there is no errors in the Firefox console.
Is there a way to execute this script right after the object has been loaded?
use
$(document).ready(function() {
(function() {
var container = d3.select(".myContainer");
alert("container: " + container);
})();
});
i have a problem with my page.
When i click on a link on my page, it will load a external html inside a div in the page. the div with the id="div1". (AJAX)
It works perfect.
the external html-page which has been loaded includes a div with the id="rex".
My Problem is:
i have a script, which must add content in the div (with the id="rex")
i wrote the script in the external file, but it doesn't run.
probably i must write my script in the page and not in the external html-file.
here the script Number 3:
$('#rex').ready(function() {
var url="genredetail.php";
var activitydetail = sessionStorage.activitydetail;
$.getJSON(url,function(json){
$.each(json.genredetail,function(i,item){
if(item.name == activitydetail){
$('<p class="excerpt">' + item.beschreibung3 + '</p>').appendTo('#rex');
}
});
});
});
This script must run when the external file (with the div id="rex") has been loaded. But it doesn't :-(
What can i do? Is the problem that the script runs before the page get the <div id="rex">?
Thanks in advance, and sorry my bad english :-S
A picture for more clearness
the script number 1 makes the link.
when i click on a link, the script number 2, let the site load in the div1.
The script number 3 must fill the div="rex" with informations. but it doesn't run.
try onload
$('div').on("load","#rex",function() {
do something
});
Try using setInterval, so it check the element rex every 0.5 s
var myInterval = setInterval(function(){
if ($("#rex").length)
{
var url="genredetail.php";
var activitydetail = sessionStorage.activitydetail;
$.getJSON(url,function(json){
$.each(json.genredetail,function(i,item){
if(item.name == activitydetail){
$('<p class="excerpt">' + item.beschreibung3 + '</p>').appendTo('#rex');
clearInterval(myInterval);
}
}, 500);
You need to reload the script if it is already loaded. As you said you are loading the external html inside a div, does it include the external js file you are using? if not please include it.
I'm trying to run my site's script.js main javascript file inside my tinyMCE instance. The idea is to have functionality, such as my sites slideshow, also running inside tinyMCE for optimal realistic editing.
I'm not even sure this is possible how I intend it.
Here's the function I use to initialize:
function set_html_tinymce() {
tinymce.init({
selector:'#edit_html_textarea',
... ...
});
// LOAD jQUERY AND SCRIPT.JS INSIDE TINYMCE
var scriptLoader = new tinymce.dom.ScriptLoader();
scriptLoader.add('http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
scriptLoader.add('../js/script.js');
scriptLoader.loadQueue(function() {
alert('All scripts are now loaded.');
});
}
Here's the contents of my test script.js:
$( document ).ready(function() {
alert('a');
$('.slideshow').on('click', function() {
alert('b');
});
$('.slideshow').click(function() {
alert('c');
});
});
I get the first alert a and All scripts are now loaded., so the script.js is indeed loaded. However when I click on a .slideshow class div inside tinyMCE I get neither b nor c alert.
How can I load and run a jQuery/JS file inside tinyMCE, and have it execute in the same manner it would on the site itself?
I would love an officially supported solution but if this isn't possible I will settle for a 'hack'.
the problem is that TinyMCE uses designMode, so in order to add a js file to the iframe, you must first turn off designMode.
This solution worked for me:
var editor = $(tinymce.activeEditor.getBody())[0];
var iframe = $R('txtTinyMCE_ifr');
editor.designMode = 'off';
var script = iframe.contentDocument.createElement('script');
script.setAttribute('src', '../../scripts/tinymce/iframe.js');
editor.appendChild(script);
editor.designMode = 'on';
You should add this code to the init_instance_callback function for TinyMCE.
I'm loading some HTML and JS with AJAX:
main-page.html loads vía AJAX a page called page-to-load.html.
<!-- main-page.html -->
<html>
...
<script>
$.ajax({
type:"POST",
url:"page-to-load.html",
success:function(data) {
$("#some_id").html(data);
}
});
</script>
...
</html>
page-to-load.html includes html and a js file:
<!-- page-to-load.html --->
<script src="scripts-for-this-html.js"></script>
<p>This is a HTML page working with above external .js file</p>
As you can see, i'm loading a js file, scripts-for-this-html.js
This works perfectly. The problem is that if I loaded again (I mean, "#some_id" gets empty and loaded with page-to-load.html again) all the script (scripts-for-this-html.js) remains in the browsers memory (for example, if I have an event in this .js file, this event gets repeated as many times I had loaded the file, even if i have deleted the script element from the DOM).
Is there any way to get this work? I don't want to include all the .js files at once (ther are too many), I want to loaded and unloaded them by demand.
JavaScript unloading could theoretically be done by removing the script tag (as you are doing with .html and by eliminating all references to any objects associated with the script. This involves deleting every reference and event listener. Even one left could keep that variable's functional scope in memory causing a leak.
It would be smart to use regular expressions to remove the scripts if the have been loaded already. (Credit to #JCOC611 for the idea of stripping tags.) Something like:
var usedScripts = {};
html = html.replace(/<script\s+src="([^"]+)"><\/script>/gi, function(str, file) {
if(usedScripts[file]) {
return "";
} else {
usedScripts[file] = true;
return str;
}
});
If you have a finite number of pages, what I prefer to do is have an object:
{
myPage: {
html: 'myhtml.html',
script: 'myscript.js'
}
}
Then have a loader function which simultaneously loads the script with document.createElement('script') and loads the page with HTML. You could easily check if that script has been used and skip loading.